
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.
//测试Accepted
//要注意的一点是一旦是把A和B交换了以后,A的父节点就指向了B。这个是容易忘记的一点。
class Solution {
public:
	ListNode *swapPairs(ListNode *head) {
		ListNode* prev = NULL;
		ListNode* first = NULL;
		ListNode* second = head;
		int k = 1;
		while (second != NULL)
		{
			if (k%2 == 0)
			{
				first->next = second->next;
				second->next = first;
				if(prev != NULL)//when process prev pointer, we should be very careful
					prev->next = second;
				else head = second;
				ListNode* tmp = first;
				first = second;
				second = tmp;
			}
			prev = first;
			first = second;
			second = second->next;
			k++;
		}
		return head;
	}
};
//要注意的一点是一旦是把A和B交换了以后,A的父节点就指向了B。这个是容易忘记的一点。
#include<iostream>
using namespace std;
#define N 5
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
	ListNode *swapPairs(ListNode *head) {
		ListNode* prev = NULL;
		ListNode* first = NULL;
		ListNode* second = head;
		int k = 1;
		while (second != NULL)
		{
			if (k%2 == 0)
			{
				first->next = second->next;
				second->next = first;
				if(prev != NULL)//when process prev pointer, we should be very careful
					prev->next = second;
				else head = second;
				ListNode* tmp = first;
				first = second;
				second = tmp;
			}
			prev = first;
			first = second;
			second = second->next;
			k++;
		}
		return head;
	}
};
ListNode *creatlist()
{
	ListNode *head;
	head=NULL;
	for(int i=0; i<N; i++)
	{
		int a;
		ListNode *p;
		cin>>a;
		p = (ListNode*)malloc(sizeof(ListNode));
		p->val=a;
		p->next=head;
		head = p;
	}
	return head;
}
int main()
{
	ListNode *list=creatlist();
	Solution lin;
	ListNode *outlist=lin.swapPairs(list);
	for(int i=0; i<N; i++)
	{
		cout<<outlist->val;
		outlist = outlist->next;
	}
}leetcode_24_Swap Nodes in Pairs
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43791899