算法设计与分析(17)-- Swap Nodes in Pairs(难度:Medium)

算法设计与分析(17)

题目: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.

算法思路

问题是把一个链表的每两个节点进行交换位置。一个链表节点交换位置,按题目的要求,不能通过更改节点里的取值,实际上只需要更改节点中的next指针。所以这里的算法比较简单,我们只需要额外引入两个指针ListNode *first, *second,就可以完成任务。
(1)首先,若头指针为空直接返回NULL。若不为空,first指向头部第一个节点,接着若head->next不为空,用second指向第二个节点。然后为了交换first和second的位置,先使head指向第二个节点,再改变first和second的next取值:

ListNode *first, *second;
if (head == NULL)
    return head;
first = head;
if (head->next != NULL)
{
    second = first->next;
    head = second;
    first->next = second->next;
    second->next = first;
}

(2)注意这个时候,由于已经交换位置,实际上first才是second的下一个节点。所以接下来我们判断first->next与first->next->next是否为空,只有当两个都不为空时,我们才对他们两个节点进行交换。
交换过程也比较简单:先使用ListNode *temp取值为first,在将first->next和first->next->next重新用first和second指向他们。接着就可以通过改变他们的next取值来更变位置。

while (first->next != NULL && first->next->next != NULL)
{
    ListNode *temp = first;
    first = first->next;
    second = first->next;

    temp->next = second;
    first->next = second->next;
    second->next = first;
}

(3)最后返回头指针。

程序运行结果:

这里写图片描述

这里写图片描述

实现代码

#include <iostream>
#include <vector>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* swapPairs(ListNode* head) 
{
    ListNode *first, *second;
    if (head == NULL)
        return head;
    first = head;
    if (head->next != NULL)
    {
        second = first->next;
        head = second;
        first->next = second->next;
        second->next = first;
    }


    while (first->next != NULL && first->next->next != NULL)
    {
        ListNode *temp = first;
        first = first->next;
        second = first->next;
        temp->next = second;
        first->next = second->next;
        second->next = first;
    }
    return head;
}

int main()
{
    ListNode a1(1), a2(2), a3(3), a4(4);
    a1.next = &a2;
    a2.next = &a3;
    a3.next = &a4;
    ListNode *head = &a1;
    swapPairs(head);

    while (head != NULL)
    {
        cout << head->val << endl;
        head = head->next;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值