给出一个链表 1->2->3->null, 这个翻转后的链表为 3->2->1->null
步骤是这样的:
1. 新建空节点: None
- 1->None
- 2->1->None
- 3->2->1->None
代码就非常简单了:
- # -*- 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
- temp = None
- while pHead:
- cur = pHead.next
- pHead.next = temp
- temp = pHead
- head = cur
- return temp
来源: http://www.bubuko.com/infodetail-2506575.html