题目描述:
输入一个链表,反转链表后,输出新链表的表头。
思路:
思路1:
从头到尾遍历链表,每到一个新元素时,定义两个指针preNode和nextNode,preNode指向当前元素的上一个元素,nextNode指向当前元素的下一个元素。改变当前元素的指向为preNode,并将preNode和nextNode均向右移动一位。
Python实现1:
// An highlighted block
def ReverseList(self, pHead):
preNode = None
while pHead:
nextNode = pHead.next
pHead.next = preNode
preNode, pHead = pHead, nextNode
return preNode
原文:https://blog.csdn.net/u010005281/article/details/79873244
思路2:使用递归实现。不断递归到链表的尾端,更新尾端元素指向其上一个元素,并断开上一个元素的指向。
// An highlighted block
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead or not pHead.next:
return pHead
nextNode = pHead.next
newHead = self.ReverseList(nextNode)
nextNode.next = pHead
pHead.next = None
return newHead
# write code here
Python实现3:
// An highlighted block
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
last = None
while pHead:
tmp = pHead.next
pHead.next=last
last=pHead
pHead=tmp
return last