Life has a funny way of working out, just when you start to believe it never will
反转链表
Posted onEdited onIn数据算法Word count in article: 1.5kReading time ≈1 mins.
反转链表
1->2->3->4->5->NULL
5->4->3->2->1->NULL
迭代法
python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
class Solution: def reverseList(self, head: ListNode) -> ListNode: prev = None cur = head while cur: a = cur.next cur.next = prev prev = cur cur = a return prev
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList(head *ListNode) *ListNode { var prev *ListNode cur := head for { if cur == nil { break } // 获取指向当前的下一个 a := cur.Next // 当前的指向前一个 cur.Next = prev // 为下次循环准备,前一个变成当前的 prev = cur // 当前的变成下一个 cur = a } return prev }
时间复杂度:O(n),假设 n 是列表的长度,时间复杂度是 O(n)。 空间复杂度:O(1)。
递归
python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
class Solution: def reverseList(self, head: ListNode) -> ListNode: def handle(cur, prev): # 终止条件 if not cur: return prev # 递归执行 res = handle(cur.next, cur) # 重复逻辑,将指针指向前一个,前后逻辑不影响 cur.next = prev return res return handle(head, None)