LeetCode 024. Swap Nodes in Pairs

Swap Nodes in Pairs

 

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.


這道題交換node不難,關鍵是前一對node交換完之後,還必須記錄前一對後一個節點的地址,以便其next直線下一對節點的前一個node.

如下圖所示,交換後,2節點指向1節點,2節點此時成爲頭結點。1節點指向下一對節點的首節點。將這些關係縷清了也就不難了,都是指針操作。


代碼如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    ListNode *swapPairs(ListNode *head) 
    {
        if(!head)
            return NULL;
        struct ListNode * p = head;
        struct ListNode * q = NULL;
        struct ListNode * prev = NULL;
        if(head->next)
            head = head->next; //第二個節點將變成頭結點
        else
            return head;

        while(p->next)
        {
            q = p->next;
            p->next = q->next;
            q->next = p;
            prev = p;
            if(p->next && p->next->next)
            {
                p = p->next;
                prev->next = p->next;
            }
            else 
                break;
        }
        
        return head;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章