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

被折叠的 条评论
为什么被折叠?



