输入一个链表,反转链表后,输出新链表的表头。
# -*- 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
last = None
while pHead:
# 反转链表指向
temp = pHead.next
pHead.next = last
# 向前移动一步
last = pHead
pHead = temp
return last
思路:要反转链表,肯定是要把ListNode.next属性的改为本结点的上一个结点。所以需要两个指针,但是如果直接把前指针直接指向后指针,整个链表就断了。这样就没法让前后指针走下去,所以需要temp 保存前指针的原来的下一个结点,为了前指针能够沿着旧方向向前遍历。