python 反转列表

翻转一个链表

样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

步骤是这样的:

1. 新建空节点:None
2. 1->None
3. 2->1->None
4. 3->2->1->None

代码就非常简单了:

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 class Solution:
 7     # 返回ListNode
 8     def ReverseList(self, pHead):
 9         # write code here
10         temp = None
11         while pHead:
12             cur = pHead.next
13             pHead.next = temp
14             temp = pHead
15             head = cur
16         return temp
原文地址:https://www.cnblogs.com/shunyu/p/8469054.html