zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    [非专业翻译] Mapster
    Js 之TreeGrid使用
    Java 之无限级分类
    Layui 之layedit动态赋值
    Java 之配置修改代码不重启服务器
    Java 之QueryRunner实现增删改查
    Java 之c3p0连接池 + dbutils例子
    PHP 之阿里云短信插件
    Java 之数据库工具类
    Java 之myEclipse破解代码
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9120733.html
Copyright © 2011-2022 走看看