本系列文章为《剑指Offer》刷题笔记。
刷题平台:牛客网
思路
我们使用三个指针,分别指向当前遍历到的结点、它的前一个结点以及后一个结点。
需要注意反转过程中不要丢了节点。可以使用两个指针,也可以使用三个指针。
【解法1】两个指针
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
cur , prev= pHead,None
while cur:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev
【解法2】三个指针
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
prev=None
cur = pHead
post = cur.next
while post:
cur.next = prev
prev = cur
cur = post
post = post.next
cur.next = prev # 最后还要给prev一下
return cur
注:至此,是cur完成了所有链表元素的遍历。prev也可以,但还要加一句prev = cur
参考 https://www.jb51.net/article/190180.htm