单向链表中间节点
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <utility>
#include <vector>
#include <list>
#include <ostream>
#include <sstream>
#include <unordered_map>

using namespace std;

struct LinkList {
int val_;
LinkList *next_;

explicit LinkList(int val, LinkList *next = nullptr)
: val_(val), next_(next) {}
};

LinkList *buildLink(unordered_map<std::string, pair<int, std::string >> &mp, std::string &start) {
auto len = mp.size();
LinkList *link = nullptr;
LinkList *re = nullptr;
for (int i = 0; i < len; ++i) {
auto &[val, end] = mp[start];
start = end;
auto link_node = new LinkList(val, nullptr);
if (link == nullptr) {
link = link_node;
re = link; // 记录头节点,后续返回
} else {
link->next_ = link_node; // 更新节点
link = link->next_;
}
}
return re;
}

int findMiddle(LinkList *head, int len) {
int middle = len / 2;
auto tmp = head;
for (int i = 0; i < middle; ++i) {
tmp = tmp->next_;
}
return tmp->val_;
}

void clear(LinkList *head) {
while (head != nullptr) {
auto tmp = head->next_;
head->next_ = nullptr;
delete head;
head = tmp;
}
}

int main() {
std::string startAddr;
int num;

std::string data;
getline(cin, data);
istringstream iss(data);
iss >> startAddr >> num;

unordered_map<std::string, pair<int, std::string >> map_;
for (int i = 0; i < num; ++i) {
getline(cin, data);
istringstream iss2(data);
std::string start, end;
int val;
iss2 >> start >> val >> end;
map_[start] = make_pair(val, end);
}

auto link = buildLink(map_, startAddr);

cout << findMiddle(link, num) << endl;

clear(link);

return 0;
}

buildLink 构建链表的时候,记得更新节点信息,同时记录最开始的 头结点信息返回。

程序的最后,还可以把 链表的对内存回收一下,尽管你可以考虑用智能指针,更加优雅。