题目描述:
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.
分析:
题意:给定一个单链表,对于每两个相邻的结点,交换它们的顺序,并返回结果。
思路:这道题考察头插法(之前有说明,头插法逆序,尾插法正序)。为了方便操作,我们用指针h建立一个空结点(方便指针s的操作,同时保存最终结果)。我们用一个flag标记来说明当前结点是每一对结点的开始或者结尾。flag为true时,一对结点已经交换完毕,然后接下去处理另一对结点,此时指针s指向下一对结点的开始位置。
假设单链表包含n个结点,那么时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// Exceptional Case:
if(!head || !head->next){
return head;
}
ListNode * p = head, *r;
ListNode *h = new ListNode(-1), *s = h;
bool flag = false;
// every two nodes: head insert method
while(p){
r = p;
p = p->next;
r->next = s->next;
s->next = r;
flag = !flag;
if(!flag){
s = s->next->next;
}
}
return h->next;
}
};