题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路:扫描链表,不断将结点插入到新链表的头部,
Python代码如下:
#-*- 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:
return pHead
dummy = ListNode(0)
dummy.next = pHead
temp1 = pHead
temp2 = pHead.next
while temp2:
temp3 = temp2.next
temp2.next = temp1
dummy.next = temp2
temp1 = temp2
temp2 = temp3
pHead.next = None
return dummy.next