1025 反转链表

问题描述

问题描述

​ 这道题我是采用map+vector的方式,以address为key将节点先存在map中,然后遍历出链表的address存在vector中。这样只需要处理vector中的地址,然后去map中查地址对应的数据就可以了。

数据结构

上面是我画的数据结构示意图(有点丑.....)

问题分析

这个题的坑在输入的节点不一定是合法的节点,就是输入的节点根本就不在链表中。所以需要将这些节点排除出去。

解决方法

    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
struct node{
string address;
int data;
string next;
};

int main() {
string head;
int n,k;
cin>>head>>n>>k;
map<string,node> linknode;
//输入节点
for (int i = 0; i < n; ++i) {
string address,next;
int data;
cin>>address>>data>>next;
node temp;
temp.address = address;
temp.data = data;
temp.next = next;
linknode[address] = temp;
}
//将链表中节点的地址按顺序存储到数组
vector<string> address;
string temp = head;
for (int i = 0; temp != "-1"; ++i) {
address.push_back(temp);
temp = linknode[temp].next;
}
//输出
n = address.size();
for (int i = 1; n >= k; ++i) {
for (int j = i*k - 1; j >= k*(i-1); --j,--n) {
cout<<address[j]<<" "<<linknode[address[j]].data<<" ";
if (j == k*(i-1)) {
if (n<=k) {
cout<<(i*k == address.size() ? "-1" : address[(i*k)] )<<endl;
}
else cout<<address[(i+1)*k-1]<<endl;
}
else cout<<address[j-1]<<endl;
}
}
for (int i = address.size() - n; i < address.size(); ++i) {
cout<<address[i]<<" "<<linknode[address[i]].data<<" "<<linknode[address[i]].next<<endl;
}
return 0;
}

​ 我用的方法在输出的时候有一些绕弯子,要做很多判断,其实只需要写一个你逆序函数,对数组内元素进行分组逆序再顺序输出就可以解决了。

刚做这题时有点被这题目唬住了,但是仔细想想其实非常简单。在做题的时候不能被一个思路框住,发散的思考才能找到较优的解决方案。