-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist_res_lqA.cpp
51 lines (48 loc) · 1 KB
/
linkedlist_res_lqA.cpp
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
// 翻转链表
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
class ListNode
{
public:
int val;
ListNode *next;
ListNode (int val) // 构造函数
{
this->val = val;
this->next = NULL;
}
};
int main()
{
int n;
while (1) {
cin >> n;
if (n == -1) break;
ListNode dummy(0), *cur = &dummy;
// 链表初始化
for (int i = 0; i < n; ++i) {
int val; cin >> val;
cur->next = new ListNode(val);
cur = cur->next;
}
// 链表翻转
ListNode *head = dummy.next;
ListNode *prev = NULL;
while (head) {
ListNode *next = head->next;
head->next = prev;
prev = head;
head = next;
}
head = prev;
// 输出链表
while (head->next) {
cout << head->val << " ";
head = head->next;
}
cout << head->val << endl;
}
}