# 206. 反转链表
力扣原题链接(点我直达) (opens new window)
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
1
2
2
进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
# 第一版,反转
执行用时 :12 ms, 在所有 cpp 提交中击败了78.92%的用户
内存消耗 :9.2 MB, 在所有 cpp 提交中击败了20.28%的用户
struct ListNode {
int val;
ListNode* next;
ListNode(int x) :val(x), next(nullptr) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* curr = head;
ListNode* next = nullptr;
while (curr) {
next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
}
return pre;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22