24. Swap Nodes in Pairs(unsolved)

本文介绍了一种链表中相邻节点的交换算法实现,通过使用常数空间复杂度完成节点位置的互换,而非修改节点值。该算法适用于1->2->3->4形式的链表,能将其转换为2->1->4->3的形式。

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.

Subscribe to see which companies asked this question

/**
 * 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) {
        ListNode* buffer=new ListNode(0);
        buffer->next=head;
        ListNode* prev=buffer;
        while(head&&head->next)
        {
            prev->next=head->next;
            head->next=head->next->next;
            prev->next->next=head;
            prev=prev->next->next;
            head=head->next;

        }
        return buffer->next;
    }
};

二刷时,解法更简单,而且更清晰。
思路就是,要用三个指针,head,l1,l2,分别指向要调换的两个节点的前面那个节点和要调换的两个节点。所以这就是为什么刚开始要让head指向newhead那个节点的原因(让他初始化为要调换的两个节点的前头)。

/**
 * 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 head;
        ListNode* newhead=new ListNode(0);
        newhead->next=head;
        ListNode* l1=head;
        ListNode* l2=head->next;
        head=newhead;
        while(l2&&l1)
        {
            head->next=l2;
            l1->next=l2->next;
            l2->next=l1;
            head=l1;
            l1=l1->next;
            if(l1) l2=l1->next;
        }
        return newhead->next;



    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值