码迷,mamicode.com
首页 > 编程语言 > 详细

python 反转列表

时间:2018-02-25 14:40:25      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:while   ext   elf   odi   链表   one   foo   data-   面试   

翻转一个链表

 

样例

给出一个链表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

 

 

 

 

 

 

 

 

 

python 反转列表

标签:while   ext   elf   odi   链表   one   foo   data-   面试   

原文地址:https://www.cnblogs.com/shunyu/p/8469054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!