【题目】反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnnhm6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1.0 自己做:
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution: 7 def reverseList(self, head: ListNode) -> ListNode: 8 if head == []: 9 return head 10 if len(head)%2 == 0: 11 length = len(head)/2 12 else: 13 length = (len(head)+1)/2 14 for i in range(int(length)): 15 head[i], head[-i-1] = head[-i-1], head[i] 16 return head
感觉自己做成了数组,不懂链表啊......
Python 数据结构之链表:https://zhuanlan.zhihu.com/p/60057180