首页 > 编程语言 > 详细

LintCode Python 简单级题目 35.翻转链表

时间:2017-06-07 11:45:34      阅读:327      评论:0      收藏:0      [点我收藏+]

题目描述:

 

翻转一个链表

 

样例

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

 

挑战 

在原地一次翻转完成

 

 

题目分析:

在原地一次翻转完成

循环head链表,将链表中的元素从表头依次取出指向新链表即可。

源码:

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of the linked list.
    @return: You should return the head of the reversed linked list. 
                  Reverse it in-place.
    """
    def reverse(self, head):
        # write your code here
        if head is None: return None
        p = head
        cur = None
        pre = None
        while p is not None:
            cur = p.next
            p.next = pre
            pre = p
            p = cur
        return pre

  

LintCode Python 简单级题目 35.翻转链表

原文:http://www.cnblogs.com/bozhou/p/6956185.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!