LintCode Python 簡單級題目 35.翻轉鏈表


題目描述:

 

翻轉一個鏈表

 

樣例

給出一個鏈表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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM