-
Notifications
You must be signed in to change notification settings - Fork 24
/
reverse-a-linked-list.cpp
70 lines (55 loc) · 1.21 KB
/
reverse-a-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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Reverse a linked list
// Change the links between the nodes of a linked list to reverse it
//
// https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
//
#include "linked-list.hpp"
Node* Reverse(Node *head);
int main()
{
int t;
std::cin >> t;
while (t--)
{
std::vector<int> v1, v2;
Node *a = read_nodes();
v1 << a;
std::reverse(v1.begin(), v1.end());
a = Reverse(a);
v2 << a;
if (v1 == v2)
std::cout << "Right Answer!" << std::endl;
else
std::cout << "Wrong Answer!" << std::endl;
free_nodes(a);
}
return 0;
}
/*
Reverse a linked list and return pointer to the head
The input list will have at least one element
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* Reverse(Node *head)
{
// Complete this method
if (head == NULL) return NULL;
if (head->next == NULL) return head;
Node *node, *prev = NULL, *old;
while (head)
{
node = new Node;
node->data = head->data;
node->next = prev;
prev = node;
old = head;
head = head->next;
delete old;
}
return node;
}