forked from jnozsc/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse_Linked_List.cpp
47 lines (44 loc) · 955 Bytes
/
Reverse_Linked_List.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
/*
Reverse a linked list.
Example
For linked list 1->2->3, the reversed linked list is 3->2->1
*/
#include "lintcode.h"
using namespace std;
/**
* Definition of ListNode
*
* class ListNode {
* public:
* int val;
* ListNode *next;
*
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode* reverse(ListNode* head) {
// write your code here
if (!head || !head->next) {
return head;
}
ListNode* first = head;
ListNode* second = head->next;
first -> next = NULL;
while (second) {
ListNode* nextSecond = second->next;
second->next = first;
first = second;
second = nextSecond;
}
return first;
}
};