1. 程式人生 > >LeetCode ——24. 兩兩交換鏈表中的節點

LeetCode ——24. 兩兩交換鏈表中的節點

nal 交換 GC pop light names src pau ner

技術分享圖片

用一個棧來存儲奇數次的節點,奇數次先入棧,到偶數次出棧,註意下標。

#include<iostream>
#include <vector>
#include <set>
#include <functional>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <list>
#include <map>
#include <stack>
#include <algorithm>

using namespace std;
vector<string> result;
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

ListNode* swapPairs(ListNode* head) {
	if (head == nullptr)
		return nullptr;
	stack<ListNode*> Stack;
	ListNode* previous = head;
	ListNode* current = head;
	ListNode* tmp;
	if (head->next != nullptr)
	{
		tmp = head->next->next;
		head = previous->next;
		head->next = current;
		current->next = tmp;
		previous = current;
		current = tmp;
	}
	else
		return head;


	while (current != nullptr)
	{
		if (Stack.empty())
		{
			Stack.push(current);
			current = current->next;
		}
		else
		{
			tmp = current->next;
			previous->next = current;
			current->next = Stack.top();
			Stack.pop();
			current->next->next = tmp;
			previous = current->next;
			current = previous->next;
		}

	}
	return head;
}
ListNode* generate(){
	ListNode* head = new ListNode(1);
	ListNode* pos = head;
	vector<int> vi = { 2, 3, 4 ,5,6};
	for (auto i : vi)
	{
		pos->next = new ListNode(i);
		pos = pos->next;
	}
	return head;
}

int main(int argc, char** args)
{
	ListNode* head = generate();
	ListNode* pos = head;
	while (pos != nullptr)
	{
		cout << pos->val << " ";
		pos = pos->next;
	}
	head = swapPairs(head);
	cout << endl;
	pos = head;
	while (pos != nullptr)
	{
		cout << pos->val << " ";
		pos = pos->next;
	}

	//delete
	pos = head;
	while (head != nullptr)
	{
		pos = head->next;

		delete head;
		head = pos;
	}

	system("pause");
	return 0;
}

  

LeetCode ——24. 兩兩交換鏈表中的節點