原题链接:
注意点:
1.题意理解:链表只需要逆转数量达到K的节点链,当链表原来为1→2→3→4→5→6,K=4时,只需要逆转1→2→3→4,→5→6不需要逆转,原样输出即可。
2.输出注意:地址为5位,需要使用<iomanip>对cout输出格式进行控制,让地址为4的输出为00004。
代码:
#include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <iomanip>
using namespace std;
#define endl '\n'
int headAdd, N, K;
struct node {
int address;
int data;
int next;
};
vector<node> nodes;
map<int, node> m;
stack<int> s;//存储node的address
bool flag = true;//是否是第一次输出
void seqPop() {
while (!s.empty()) {
int topAdd = s.top();
if (flag) {//第一个
cout << setw(5) << setfill('0') << topAdd;
cout<< ' ' << m[topAdd].data << ' ';
flag = false;
}
else {
cout << setw(5) << setfill('0') << topAdd;
cout << endl;
cout << setw(5) << setfill('0') << topAdd;
cout<< ' ' << m[topAdd].data << ' ';
}
s.pop();
}
}
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> headAdd >> N >> K;
for (int i = 0; i < N; i++) {
node temp;
cin>>temp.address>>temp.data>>temp.next;
m[temp.address] = temp;
}
int atAdd = headAdd;
int lastAdd = headAdd;
while (atAdd != -1) {
//压入栈
s.push(atAdd);
if (s.size() == K) {
//栈内弹出
seqPop();
lastAdd = atAdd;
}
atAdd = m[atAdd].next;
}
//处理栈内没有弹出的,不需要逆序输出
atAdd = m[lastAdd].next;
while (atAdd != -1) {
cout << setw(5) << setfill('0') << atAdd;
cout << endl;
cout << setw(5) << setfill('0') << atAdd;
cout << ' ' << m[atAdd].data << ' ';
atAdd = m[atAdd].next;
}
cout << -1;
return 0;
}