码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_24_Swap Nodes in Pairs

时间:2015-02-13 11:44:24      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   linked_list   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


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

标签:c++   leetcode   linked_list   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43791899

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!