使用数组模拟模拟链表,这个方法有点取巧
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
void listReverse(vector<vector<string>>& nodeList, int start, int end){
if(end >= nodeList.size())
return;
while(start < end){
vector<string> tmp = nodeList[start];
nodeList[start] = nodeList[end];
nodeList[end] = tmp;
start++;
end--;
}
}
int main(){
int n, k;
string startAddr;
cin >> startAddr >> n >> k;
unordered_map<string, int> find_addr;
vector<vector<string>> nodeList(n, vector<string>(3, ""));
for(int i = 0; i < n; i++){
string nodeAddr, nextAddr;
int data;
cin >> nodeAddr >> data >> nextAddr;
nodeList[i][0] = nodeAddr;
nodeList[i][1] = to_string(data);
nodeList[i][2] = nextAddr;
find_addr[nodeAddr] = i;
}
vector<vector<string>> List;
string nextAddr = startAddr;
while(nextAddr != "-1"){
int index = find_addr[nextAddr];
List.push_back(nodeList[index]);
nextAddr = nodeList[index][2];
}
for(int i = 0; i < List.size(); i = i + k){
listReverse(List, i, i + k - 1);
}
for(int i = 0; i < List.size(); i++){
if(i < List.size() - 1){
List[i][2] = List[i + 1][0];
cout << List[i][0] <<" "<< List[i][1] <<" "<< List[i][2] << endl;
}
else{
List[i][2] = "-1";
cout << List[i][0] <<" "<< List[i][1] <<" "<< List[i][2] << endl;
}
}
return 0;
}