天天看点

【LeetCode】011 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.

链表中,每两个交换一下位置。

https://leetcode.com/problems/swap-nodes-in-pairs/

【解析】

看了某人的解析,图画的出神入化,不禁也想模仿。

http://blog.csdn.net/summerdj/article/details/51457424

建立链表如下:

【LeetCode】011 Swap Nodes in Pairs 两两换位

head为当前头指针

pre为前一个指针

q为当前操作临时指针

p为交换后的链表的头指针的前一个指针

ListNode* p=new ListNode(0);
        p->next=head->next;
        ListNode* pre=p;
        ListNode* q=head->next;
           
【LeetCode】011 Swap Nodes in Pairs 两两换位

进入第一次循环:

head->next=q->next;  
                q->next=head;
                head=head->next;
           
【LeetCode】011 Swap Nodes in Pairs 两两换位
pre->next=q;
                pre=q->next;
           
【LeetCode】011 Swap Nodes in Pairs 两两换位

进入第二次循环:

q=head->next;
           
【LeetCode】011 Swap Nodes in Pairs 两两换位
head->next=q->next;  
                q->next=head;
                head=head->next;
           
【LeetCode】011 Swap Nodes in Pairs 两两换位
pre->next=q;
                pre=q->next;
           
【LeetCode】011 Swap Nodes in Pairs 两两换位

以此类推,当发现next对应的地址为NULL时,则链表遍历结束

p->next 即为整个链表的开头,return,结束。

【程序】

/**
 * 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==NULL || head->next==NULL) return head;
        ListNode* p=new ListNode(0);
        p->next=head->next;
        ListNode* pre=p;
        ListNode* q=head->next;
        while(head->next){
            q=head->next;
            if(q->next){          
                head->next=q->next;  
                q->next=head;
                head=head->next;
                pre->next=q;
                pre=q->next;
            }
            else{
                head->next=NULL;
                q->next=head;
                pre->next=q;
            }

        }
    return p->next;
    }
};