自学内容网 自学内容网

Leetcode 206.反转链表

题目链接:206. 反转链表 - 力扣(LeetCode)

题目描述:

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

解题思路:

定义cur,pre两个指针,分别指向当前节点和上一个节点,

  1. 用tmp暂存当前节点的next
  2. 将当前节点指向反转
  3. pre指针更新到当前cur指针
  4. cur指针更新到已暂存cur.next的tmp

代码:

class ListNode:
   def __init__(self,val = 0,next = None):
          self.val = val
          self.next = next

class Solution:
   def reverseList(self,head:Optional[ListNode])->Optional[ListNode]:
       pre = None
       cur = head
       while cur:
          tmp = cur.next
          cur.next = pre
          pre = cur
          cur = tmp
       return pre
       
       


原文地址:https://blog.csdn.net/qq_64631161/article/details/142746340

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!