This repository has been archived by the owner on Jan 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
reverse_list.cpp
84 lines (76 loc) · 1.5 KB
/
reverse_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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
struct Node
{
int data;
Node* next;
Node* prev;
};/*
Reverse a doubly linked list, input list may also be empty
Node is defined as
struct Node
{
int data;
Node *next;
Node *prev
}
*/
Node* Reverse(Node* head)
{
if(head == NULL || head->next == NULL) return head;
Node *p = head;
Node *q = head->next;
if(q->next == NULL) {
q->next = p;
q->prev = NULL;
p->next = NULL;
p->prev = q;
return q;
}
while(q->next != NULL) {
if(p == head)
p->next = NULL;
Node *_next = q->next;
q->next = p;
p->prev = q;
p = q;
q = _next;
}
q->next = p;
p->prev = q;
q->prev = NULL;
return q;
}Node* Insert(Node *head, int data)
{
Node *temp = new Node();
temp->data = data; temp->prev = NULL; temp->next = NULL;
if(head == NULL) return temp;
head->prev = temp;
temp->next = head;
return temp;
}
void Print(Node *head) {
if(head == NULL) return;
while(head->next != NULL){ cout<<head->data<<" "; head = head->next;}
cout<<head->data<<" ";
while(head->prev != NULL) { cout<<head->data<<" "; head = head->prev; }
cout<<head->data<<"\n";
}
int main()
{
int t; cin>>t;
Node *head = NULL;
while(t--) {
int n; cin>>n;
head = NULL;
for(int i = 0;i<n;i++) {
int x; cin>>x;
head = Insert(head,x);
}
head = Reverse(head);
Print(head);
}
}