Skip to content

Commit 1270328

Browse files
authored
Create 206_Reverse Linked List.cpp
1 parent fcdc0a3 commit 1270328

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Diff for: 206_Reverse Linked List.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* reverseList(ListNode* head) {
14+
15+
if(!head)
16+
return NULL;
17+
18+
ListNode *before = NULL;
19+
ListNode *current = head;
20+
ListNode *after = head->next;
21+
22+
while(after){
23+
24+
current->next = before;
25+
before = current;
26+
current = after;
27+
after = after->next;
28+
}
29+
//最後一個current還指著null,要將它指回前一個
30+
current->next = before;
31+
32+
return current;
33+
34+
}
35+
};

0 commit comments

Comments
 (0)