206. 反转链表

解1

遍历翻转

# 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:
        
        if not head or not head.next:
            return head
        
        # 保存头部节点 之后会是尾部节点
        tail = head
        
        pre = head
        cur = head.next
        
        while cur:
            # 之后更新 cur 会使用此时cur的next
            temp = cur.next
            
            # 翻转
            cur.next = pre
            # 更新
            pre = cur
            cur = temp
            
        # 指向翻转后的头部节点
        head = pre
        # 尾部节点next指向空
        tail.next = None
        
        return head
        

相关文章:

  • 2022-12-23
  • 2022-01-14
  • 2021-04-21
  • 2021-12-26
  • 2021-05-15
  • 2021-09-02
  • 2021-07-05
猜你喜欢
  • 2021-07-10
  • 2021-12-29
  • 2021-08-25
相关资源
相似解决方案