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.
移动链表即可 , 在链表头加一个节点,方便处理头节点,只要返回的时候,返回头结点的下一个即可。
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL) return NULL;
ListNode * H = new ListNode(0);
H->next = head;
ListNode *p, *q;
ListNode *visitHead = H;
while (visitHead->next != NULL)
{
p = visitHead->next;
q = p->next;
if (q == NULL) return H->next; //如果是奇数,最后一组不用再处理,直接返回
p->next = q->next; //交换
q->next = p;
visitHead->next = q;
visitHead = p; //移动末尾节点到这组的
}
return H->next;
}
};
int main()
{
ListNode * p1 = new ListNode(1);
p1->next = new ListNode(2);
p1->next->next = new ListNode(3);
Solution a;
ListNode * p = a.swapPairs(p1);
while (p != NULL)
{
cout << p->val << " ";
p = p->next;
}
system("pause");
return 0;
}