-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path206-reverse-linked-list.cpp
More file actions
46 lines (40 loc) · 1.1 KB
/
Copy path206-reverse-linked-list.cpp
File metadata and controls
46 lines (40 loc) · 1.1 KB
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
// 206. Reverse Linked List
//
// Reverse a singly linked list.
// click to show more hints.
// Hint:
// A linked list can be reversed either iteratively or recursively. Could you implement both?
// Subscribe to see which companies asked this question
//
// Tags: Linked List
//
// https://leetcode.com/problems/reverse-linked-list/
#include <iostream>
#include <gtest/gtest.h>
#include <list/list.h>
using namespace std;
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return NULL;
ListNode *prev = NULL;
while(head){
ListNode *next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
};
TEST(leetcode_206_reverse_linked_list, Basic)
{
Solution *solution = new Solution();
ListNode *head = list_init({1, 2, 3, 4, 5});
ListNode *expected = list_init({5, 4, 3, 2, 1});
EXPECT_TRUE(list_equal(expected, solution->reverseList(head)));
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}