-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreverse_ll.cpp
More file actions
127 lines (88 loc) · 2.47 KB
/
reverse_ll.cpp
File metadata and controls
127 lines (88 loc) · 2.47 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<bits/stdc++.h>
using namespace std;
struct node{
int value;
struct node* nextNode;
};
typedef struct node nd;
nd* head = NULL;
void addNew(int val){
nd *n = (nd*) malloc(sizeof(nd));
n->nextNode = head;
n->value = val;
head = n;
}
void displayAll(){
nd* temp = head;
while(temp != NULL){
cout << temp->value << " ";
temp = temp->nextNode;
}
cout << endl;
}
int nthNode(int n){
nd* temp = head;
for(int i = 0; i < n-1; i++) temp = temp->nextNode;
return temp->value;
}
void delNth(int n){
nd* temp = head;
for (int i = 0; i < n-2; i++) temp = temp->nextNode;
nd* temp2 = temp->nextNode;
temp->nextNode = temp2->nextNode;
}
void insertNth(int n, int val){
nd* ptr = (nd*) malloc(sizeof(nd));
nd* temp = head;
for(int i = 0; i < n-2; i++) temp = temp->nextNode;
ptr->nextNode = temp->nextNode;
ptr->value = val;
temp->nextNode = ptr;
}
int printrev(nd* ptr){
//bsse case
if(ptr->nextNode == NULL) return ptr->value;
//recursive case
// int temp = printrev(ptr->nextNode);
cout << printrev(ptr->nextNode) << " ";
return ptr->value;
}
int main(){
int cs, temp;
while(cs != 9){
cout << "Press 1 to add new element\nPress 2 to display all\nPress 3 to find value at a certian node\nPress 4 to delete an element\nPress 5 to insert at nth position\nPress 6 to print in reverse\nPress 9 to Exit" << endl;
cin >> cs;
switch(cs){
case 1:
cout << "Enter the value to be inserted" << endl;
cin >> temp;
addNew(temp);
break;
case 2:
displayAll();
break;
case 3:
cout << "value of which node do you want to access" << endl;
cin >> temp;
cout << nthNode(temp) << endl;
break;
case 4:
cout << "Which node do you want to delete" << endl;
cin >> temp;
delNth(temp);
break;
case 5:
cout << "Enter position" << endl;
int t2;
cin >> t2;
cout << "Enter value" << endl;
cin >> temp;
insertNth(t2, temp);
break;
case 6:
cout << printrev(head);
cout << endl;
break;
}
}
}