题目:输入一个链表,反转链表后,输出新链表的表头。
分析:
- 先声明三个节点,分别记录当前,前一个和后一个
- 记录下一个 next = cur.next
- 修改节点指向,cur.next = pre
- 分别后移 pre = cur,cur=next
# -*- 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 pHead is None:
return pHead
pre = None
cre = pHead
next = None
while cre is not None:
next = cre.next
cre.next = pre
pre = cre
cre = next
return pre