首页 > 其他 > 详细

leetcode#24 Swap Nodes in Pairs

时间:2018-09-29 13:50:31      阅读:170      评论:0      收藏:0      [点我收藏+]

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

示例:

给定 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;
    }
};

leetcode#24 Swap Nodes in Pairs

原文:https://www.cnblogs.com/lsaejn/p/9723091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!