输入一个链表,反转链表后,输出链表的所有元素。
思路:定义三个指针
node1指针指向原链表中第一个结点,且作为最后一个结点
node2指针.next指向node1结点
temp指针指向node2结点的下一个结点
#coding:utf-8
class LiseNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
def ReverseList(self,pHead):
if pHead is None:
return pHead
node1 = pHead
node2 = pHead.next
#node1结点为尾结点
node1.next = None
while node2 is not None:
temp = node2.next
node2.next = node1
node1 = node2
node2 = temp
return node1
if __name__ == '__main__':
node1 = LiseNode(10)
node2 = LiseNode(11)
node3 = LiseNode(12)
node4 = LiseNode(13)
node5 = LiseNode(14)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = None
s = Solution()
print(s.ReverseList(node1).val)