-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList1.cpp
More file actions
133 lines (124 loc) · 2.69 KB
/
LinkedList1.cpp
File metadata and controls
133 lines (124 loc) · 2.69 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
128
129
130
131
132
133
/* Author: Ananth Madhavan
* 9th Nov 2013
* Linked list traversal problem samples.
*/
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class StackImplementation {
public:
struct node{
node *next;
int item;
};
node *top;
StackImplementation(){
top=0;
int error=0;
}
~StackImplementation(){
node *ptr=top;
while(ptr){
top=top->next;
ptr->next=0;
delete ptr;
ptr=top;
}
}
int size=0;
void push(int n){
node *t=new node();
t->item=n;
t->next=top;
top=t;
size++;
cout<<"Item pushed."<<endl;
}
int pop(){
if(size==0){
cerr<<"\n Stack underflow.";
exit(0);
}
else{
int temp=top->item;
top=top->next;
size--;
return temp;
}
}
void traverse(){
node *iterator= new node();
iterator=top;
int i=1;
while(iterator){
cout<<"Item "<<i<<":"<<iterator->item<<endl;
iterator=iterator->next;
++i;
}
cout<<"Press <enter> to continue.";
cin.get();
}
void insert(){
//Insert given element at a given position.
int p;
cout<<"\n Enter the position you want to insert element(1-5):";
cin>>p;
int e;
cout<<"\n Enter the element:";
cin>>e;
node *iterator=new node();
iterator=top;
int i=1;
while(iterator && i<p-1){
iterator=iterator->next;
++i;
}
node *element= new node();
element->next=iterator->next;
iterator->next=element;
element->item=e;
traverse();
}
};
int main(){
StackImplementation s;
char choice=' ';
while(choice!='6'){
// system("clear");
cout<<"What do you want to do?"<<endl;
cout<<"1) Push an element."<<endl
<<"2) Pop an element."<<endl
<<"3) Insert an element."<<endl
<<"4) Delete an element."<<endl
<<"5) Print the stack."<<endl
<<"6) Exit."<<endl;
cin>>choice;cin.get();
switch(choice){
case '1':
int n;
cout<<"Enter the element to push:";
cin>>n;
s.push(n);
break;
case '2':
cout<<"The popped element is: "<<s.pop()<<endl;
break;
case '3':
s.insert();
break;
case '4':
int k;
cout<<"Enter the element position you want to delete:";
cin>>k;
// s.delete(n);
break;
case '5':
s.traverse();
break;
default:
break;
}
}
return 0;
}