题目描述
输入一个链表,反转链表后,输出新链表的表头。
#解法1:利用数组
# -*- 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
tmp=[]
if not pHead:
return
while pHead:
tmp.append(pHead.val)
pHead=pHead.next
newhead=ListNode(tmp.pop())
tmp2=newhead
while tmp:
rear=ListNode(tmp.pop())
newhead.next=rear
newhead=rear
return tmp2
#解法2:直接反转
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
pre=None
head=pHead
while head:
next=head.next
head.next=pre
pre=head
head=next
return pre