反转链表

之前在C语言数据结构(1)——线性表一文中介绍了链表及其一些常见的操作,这次介绍一下链表的反转操作。

头插法

struct ListNode* reverseList(struct ListNode* head){
     
    struct ListNode*output=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode*p=head;
    struct ListNode*q,*temp;
    
    output->next=NULL;
    while(p!=NULL)
    {
     
        temp=output->next;
        output->next=p;
        q=p->next;
        p->next=temp;
        p=q;
    }
    return output->next;
}

时间复杂度为O(n)

递归法

struct ListNode* reverseList(struct ListNode* head){
     
    if (head == NULL)
        return NULL;
    if (head -> next == NULL)
        return head;
    struct ListNode *newHead = reverseList(head -> next);
    head -> next -> next = head;
    head -> next = NULL;
    return newHead;
}

时间复杂度同样为O(n)

你可能感兴趣的:(LeetCode)