输入一个链表,反转链表后,输出新链表的表头。
# -*- 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
p=pHead
q=pHead.next
p.next=None
while q:
temp=q.next
q.next=p
p=q
q=temp
return p
if __name__ == '__main__':
head = ListNode(1)
p1 = ListNode(2) # 建立链表1->2->3->4->None;
p2 = ListNode(3)
p3 = ListNode(4)
head.next = p1
p1.next = p2
p2.next = p3
a = Solution()
p = a.ReverseList(head) # 输出链表 4->3->2->1->None
while p:
print(p.val)
p = p.next