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

      

  • 相关阅读:
    vue-amap地图组件的使用
    数据分析
    爬虫之scrapy框架
    爬虫之selenium
    记录一下最近的pwn
    内核提权姿势笔记
    CVE-2016-5343分析
    CVE-2015-8660分析
    Docker远程访问get(root)shell姿势
    Linux内核ROP学习
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9120733.html
Copyright © 2020-2023  润新知