Swap Nodes in Pairs
Problem
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.
问题
已知一个链表,每两个相邻的结点相互交换并且返回链表头指针。
例如:给定链表1->2->3->4,返回结果为链表2->1->4->3。
要求:算法的空间发杂度为O(1),算法只能修改结点,不能修改链表中的值。
思路
此题目考察的是线性链表的插入和删除,为了便于操作,给链表加上头结点,操作完成之后,将该结点删除。
代码(C++)
/**
* 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 && head->next){
//为了便于操作,加一个空的头节点
ListNode* node = new ListNode(-1);
node->next = head;
head = node;//此处注意保存头指针
while (node->next && node->next->next)
{
ListNode* node1 = node->next;
//删除结点
node->next = node1->next;
//将删除的结点插入到它的后一个结点后面
node1->next = node->next->next;
node->next->next = node1;
node = node1;
}
//删除头结点
node = head;
head = head->next;
delete node;
}
return head;
}
};