问题描述
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list’s nodes, only nodes itself may be changed.
思路分析
给一条链表,交换两个相邻的节点,然后返回链表的头。要求不改变节点的值,只进行互换,并且使用 O(1) 的空间。
我们给链表增加一个头结点,然后循环对它的next和next->next进行操作,进行交换。交换的顺序是用一个temp保存next->next的信息和指针,然后逆序按照1->3,2->1,0->2的顺序完成swap。
代码
/**
* 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* begin = new ListNode(0);
begin->next = head;
ListNode* iterator = begin;
while (iterator->next && iterator->next->next){
swap(iterator);
iterator = iterator->next->next;
}
return begin->next;
}
void swap(ListNode* iterator){
ListNode* temp = iterator->next->next;
temp->next = iterator->next->next->next;
iterator->next->next = temp->next;
temp->next = iterator->next;
iterator->next = temp;
}
};
时间复杂度:
O(n)
空间复杂度:
O(1)
反思
还可以递归处理这个问题。