欢迎来到IT嘟嘟的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

24. 两两交换链表中的节点

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

 

/*
解题思路:
递归和迭代来实现。对于迭代实现,还是需要建立dummy节点,
注意在连接节点的时候,最好画个图
*/
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}

};
ListNode* CreateListNode(int arr[], int n)
{
	ListNode* head;
	head = new ListNode(arr[0]);
	ListNode* cur;
	cur = head;
	for (int i = 1; i < n; i++)
	{
		cur->next = new ListNode(arr[i]);
		cur = cur->next;
	}
	return head;
}

class Solution 
{
public:
	ListNode* swapPairs(ListNode* head) 
	{
		ListNode *dummy = new ListNode(-1), *pre = dummy;
		dummy->next = head;
		while (pre->next && pre->next->next) 
		{
			ListNode *t = pre->next->next;
			pre->next->next = t->next;
			t->next = pre->next;
			pre->next = t;
			pre = t->next;
		}
		return dummy->next;
	}
};
int main()
{
	int n;
	cin >> n;
	int i;
	int a[100];
	for (i = 0; i < n; i++)
	{
		scanf("%d", &a[i]);
	}
	ListNode* head = CreateListNode(a, n);
	ListNode* result = Solution().swapPairs(head);
	while (result != NULL)
	{
		printf("%d ", result->val);
		result = result->next;
	}
	system("pause");
	return 0;
}

  

posted on 2019-08-26 12:26  IT嘟嘟  阅读(128)  评论(0编辑  收藏  举报

导航