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

24.Swap Nodes in Pairs

时间:2015-02-10 09:18:43      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you shouldreturn the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modifythe values in the list, only nodes itself can be changed.

HideTags

 Linked List


#pragma once
#include<iostream>
#include<queue>
using namespace std;


struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};


ListNode *swapPairs(ListNode *head) 
{
	if (!head||!head->next)
		return head;
	ListNode* result = head->next;//记录返回串的头指针
	ListNode *p1 = head->next,
			*p2 = head;//指向p的前一个节点
	//头部添加一个冗余节点,使三指针的初始状态与中间状态相同
	ListNode* p3=new ListNode(0);
	p3->next = p2;
	while (p1)
	{
		p3->next = p1;
		p1 = p1->next;
		p2->next->next = p2;
		p2->next = p1;
		if (p1)
		{
			p3 = p2; 
			p2 = p1;
			p1 = p1->next;
		}
	}
	return result;
}
void main()
{
	ListNode* l1 = new ListNode(1);
	ListNode* l2 = new ListNode(2);
	ListNode* l3 = new ListNode(3);
	ListNode* l4 = new ListNode(4);
	ListNode* l5 = new ListNode(5);
	l1->next = l2;
	l2->next = l3;
	l3->next = l4;
	l4->next = l5;
	ListNode* result = swapPairs(l1);
	while (result)
	{
		cout << result->val << ' ';
		result = result->next;
	}
	cout << endl;
	system("pause");
}



24.Swap Nodes in Pairs

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43691745

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