原地反转单链表

示例:

输入:

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

猜你喜欢

转载自blog.csdn.net/qq_39394809/article/details/84776986