Loading

leetcode#24 Swap Nodes in Pairs

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:

你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

/**
 * 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) {
        //如果首节点之前有一个结点h,那就好了,我们交换第1、2个结点,再前进2次,交换3、4个结点
        //我们可以创造这个结点,也可以先交换1,2结点,让这个结点指向新的第2个结点。这里我用的是第2种办法
        if(!head||!head->next) return head;//保证有两个结点
        auto h=head;
        auto temp=h->next->next;
        head=h->next;
        h->next->next=h;
        h->next=temp;
       //现在head:2.。。。21345//h指向1,现在我们可以交换1的后面两个,然后执行循环
        while(h->next&&h->next->next)//后2个结点存在
        {
            auto temp=h->next->next->next;//3
            auto t=h->next->next;
            h->next->next->next=h->next;
            h->next->next=temp;
            h->next=t;    
            h=h->next->next;
        }
        return head;
    }
};
posted @ 2018-09-29 12:27  老鼠阿尔吉侬  阅读(94)  评论(0编辑  收藏  举报