1. 程式人生 > >原地反轉單鏈表

原地反轉單鏈表

示例:

輸入:

A->B->C->D

輸出:

D->C->B->A

 

一種方法是以類似於陣列的形式,然後用陣列的下標索引進行反轉

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head
        p=head
        d={}
        i=0
        
        while p:
            d[i]=p
            p=p.next
            i+=1
        l=len(d)
        for i in range(l-1,0,-1):
            d[i].next=d[i-1]
        d[0].next=None
        
        return d[l-1]
        

但是上述方法的時間複雜度為O(N).

如果我們想要的時間複雜度為O(1)呢?

可以設定兩個指標:

//初始狀態
p=head->next
q=head->next->next
t=NULL

//迴圈狀態為
while(q!=NULL){
    t=q->next
    q->next=p
    p=q
    q=t
}

//迴圈結束
p->next=NULL