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

用一个栈来存储奇数次的节点,奇数次先入栈,到偶数次出栈,注意下标。

#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;
}

  

猜你喜欢

转载自www.cnblogs.com/Oscar67/p/9120733.html