算法设计与分析(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;
}