鏈表反轉&交換鏈表結點

leetcode鏈表反轉連接

要求摘要:node

反轉一個單鏈表.net

輸入: 1->2->3->4->5->NULL指針

輸出: 5->4->3->2->1->NULLcode

作法是考慮把鏈表中結點的next指向它的上一個結點,以此來進行反轉。blog

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL)
        return NULL;
    struct ListNode* pre=NULL;
    struct ListNode* p=head;
    struct ListNode* h=NULL;
    while(p)
    {
        h=p;          //h不斷變化,最終爲反轉鏈表的頭結點
        struct ListNode* tmp=p->next; //tmp不斷指向下一個結點,用於遍歷鏈表  
        p->next=pre;    //將p結點的指針域由指向p的下一個結點,轉而指向p的上一個結點
        pre=p;     //將pre設爲當前結點,取下一個結點時,pre即爲下一個結點的上一個結點
        p=tmp;             //即p=p->next,不斷取下一個結點
    }
兩兩交換鏈表中的節點

要求摘要:leetcode

給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。get

你不能只是單純的改變節點內部的值,而是須要實際的進行節點交換。it

示例:給定 1->2->3->4, 你應該返回 2->1->4->3。io

作法:class

每一次操做須要知道三個結點,當前結點的上一個結點tmp,當前結點pre,當前結點的下一個結點tail。能夠看作每三個結點一組。其中,本組當前結點pre的上一個結點tmp,是上一組的最後一個節點tail,而後對本組的pre和tail進行交換操做。

移動到下一個結點或者說移動到下一組:

具體結點交換操做步驟示意圖:

完整代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


truct ListNode* swapPairs(struct ListNode* head){
    //若是爲空返回NULL;只有一個節點原樣返回
    if(head==NULL)
        return NULL;
    if(head->next==NULL)
        return head;

    struct ListNode* tmp=NULL;  //做用是保存一次循環後的末位節點
    struct ListNode* pre=head;
    struct ListNode* tail=NULL;

    tail=head->next; //先進行一次結點交換操做是爲了肯定頭結點
    //結點交換
    pre->next=tail->next;
    tail->next=pre;
    head=tail;
    tmp=pre;  //保存末位節點

    pre=pre->next; //當前結點後移,便於下一次操做
    if(pre==NULL || pre->next==NULL) //若是鏈表只有兩個或三個結點,返回該鏈表
        return head;

    while(pre && pre->next)
    {
        tail=pre->next;
        //結點交換
        pre->next=tail->next;
        tail->next=pre;
        tmp->next=tail;
        tmp=pre; //保存末位節點

        pre=pre->next;
    }

    return head;
}

另,附上一個很簡潔的代碼:

ListNode *swapPairs(ListNode *head) {
        if (!head) return NULL;
        if (!head->next) return head;
        ListNode *temp = head->next;
        head->next = swapPairs(temp->next);
        temp->next = head;
        return temp;
    }

這段代碼原帖:http://www.javashuo.com/article/p-sleoaklt-dp.html

相關文章
相關標籤/搜索