【题目描述】
输入一个链表,反转链表后,输出新链表的表头。
【解题思路】
新建一个链表,然后遍历输入的链表,不断让新链表下一次的next值指向当前新创建的链表表头,用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 pHead == None or pHead.next == None:
return pHead
lastList = None
while pHead:
tmpList = pHead.next
pHead.next = lastList
lastList = pHead
pHead = tmpList
return lastList