PAT 1025 反转链表

294 阅读1分钟

题目链接

  1. 这道题的链表是模拟早期编程语言没有指针时链表的创建方法,如果对这个有所了解,那么这道题理解起来就简单多了,如果不了解也完全没有影响。
  2. 创建一个类将地址,数据,和下一个的地址存起来,这个就代表链表中的一个节点。
  3. 根据题目输入的数据创建一个链表,然后将链表的进行反转,接着讲内容输出即可。
#include <iostream>
#include<string>
#include<vector> 
#include<stack>
#include<map>
#include<list>
#include <algorithm>
using namespace std;
class node {
public:
	string address;
	string data;
	string next;
};
int main() {
	vector<node> res;
	map<string, node> m;
	int  n, k;
	string firstAddress;
	cin >> firstAddress >> n >> k;
	node no;
	for (int i = 0; i < n; i++) {
		cin >> no.address >> no.data >> no.next;
		m[no.address] = no;
	}

	//构建链表
	no = m[firstAddress];
	res.push_back(no);
	while (no.next != "-1") {
		no = m[no.next];
		res.push_back(no);
	}
	
	//反转操作
	auto start = res.begin(), end = start;
	for (int i = 0; i < res.size() / k; i++) {
		for (int j = 0; j < k; j++) {
			end++;
		}
		reverse(start, end);
		start = end;
	}
	//链表内容重构
	for (int i = 0; i < res.size() - 1; i++) {  //这是一个坑点,输入有一些可能是不在链表中的,怪不得最后一个测试点一直段错误
		res[i].next = res[i + 1].address;
	}
	res[res.size() - 1].next = "-1";
	//链表输出
	for (int i =0; i<res.size(); i++) {
		cout << res[i].address << " " << res[i].data << " " << res[i].next << endl;
	}
	return 0;
}