PAT 1074 Reversing Linked List 双端队列

本文介绍了一种算法,用于解决链表中每K个元素进行翻转的问题。通过使用双端队列,该算法能够高效地处理链表翻转,确保最后一个不足K个的元素保持原顺序。

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤10510^5105​​ ) which is the total number of nodes, and a positive K (≤N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.
Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

Sample Output:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

题目大意:给定一个链表和一个值K,将链表中连续的K个值反转,若链表个数不是K的倍数,最后不足K个的元素不反转。
解题思路:K个元素反转一次,首先想到的就是使用栈,在遍历链表的过程中将元素不断地push到栈中,达到K个后将元素全部弹出则为反序,这样地话最后栈中剩余的元素则处理不方便(可再使用一个栈辅助进行反序),所以考虑换用双端队列,遍历时push_back,满K个后pop_back弹出,最后剩余的再pop_front,这样就能解决。

代码:

#include <bits/stdc++.h>
using namespace std;

typedef pair<int,string> P;
typedef struct node{
	int val;
	string pre, next;
	node(){};
	node(string p, int v, string n){
		pre = p;
		val = v;
		next = n;
	}
}node;

int main(int argc, char const *argv[])
{
	string start;
	int n, K;
	cin >> start >> n >> K;
	vector<node> nodes(n);
	map<string,P> mp;
	
	for(int i = 0;i < n; i++){
		cin >> nodes[i].pre >> nodes[i].val >> nodes[i].next;
		mp[nodes[i].pre] = make_pair(nodes[i].val, nodes[i].next);
	}
	vector<node> ans;
	deque<node> temp;
	
	while(start != "-1"){
		temp.push_back(node(start, mp[start].first, mp[start].second));
		if(temp.size() == K){
			while(!temp.empty()){
				ans.push_back(temp.back()); 
				temp.pop_back();
			}
		}
		start = mp[start].second;
	}
	
	while(!temp.empty()){
		ans.push_back(temp.front());
		temp.pop_front();
	}
	
	ans[ans.size()-1].next =  "-1";
	for(int i = ans.size()-2;i >= 0; i--)
		ans[i].next = ans[i+1].pre;
	
	for(int i = 0;i < ans.size(); i++)
		cout << ans[i].pre << " " << ans[i].val << " " << ans[i].next << endl;
	
	return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值