题目:![](https://img-blog.csdnimg.cn/62410d6f5c4e4c7c8833c645bd12812d.png)
算法:
双指针法:需要改变链表的next指针的指向,直接将链表反转 ,而不用重新定义一个新的链表
首先定义一个cur指针,指向头结点,再定义一个pre指针,初始化为null。
然后就要开始反转了,首先要把 cur->next 节点用tmp指针保存一下,也就是保存一下这个节点。
为什么要保存一下这个节点呢,因为接下来要改变 cur->next 的指向了,将cur->next 指向pre ,此时已经反转了第一个节点了。
最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。
调试过程:
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
#双指针法,定义两个节点pre,cur
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = ListNode(val=None, next=cur)
#cur=head,next.....none,所以当cur = none时循环结束
while cur:
#需要一个指针在cur反转之前,保存cur.next
temp = cur.next
cur.next = pre
cur = temp
return pre
原因:逻辑不对。循环里面pre都没更新。pre永远是cur前一个指针,当cur.next指向pre后,pre应该后移遍历:pre = cur
修改后:
原因:pre初始化的时候不对。pre.next = head,head不是变量,一直是输入链表的头节点,所以一直循环。
正确代码:
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
#双指针法,定义两个节点pre,cur
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = None
#cur=head,next.....none,所以当cur = none时循环结束
while cur:
#需要一个指针在cur反转之前,保存cur.next
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre