题目描述:
输入一个链表,反转链表后,输出链表的所有元素。
思路:
用temp保存pHead的下一个节点。用newHead保存新的节点的开头。然后把pHead.next只想newHead,再移动一下 三个指针即可。
代码:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def ReverseList(self, pHead):
if not pHead or not pHead.next:
return pHead
newHead = None
while pHead:
temp = pHead.next
pHead.next = newHead
newHead = pHead
pHead = temp
return newHead