-
Notifications
You must be signed in to change notification settings - Fork 8
/
Linkedlist.cpp
112 lines (100 loc) · 1.47 KB
/
Linkedlist.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
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
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head = NULL;
void create_list();
void display();
void insert_at_beginning(int);
void insert_(int ,int );
void delete_(int);
int main()
{
create_list();
display();
insert_at_beginning(24);
display();
insert_(25,2);
display();
delete_(2);
display();
return 0;
}
void create_list()
{
cout << "Enter the number of elements" << endl;
int num,i;
cin >> num;
Node *ptr = head;
for(i = 0;i<num;i++)
{
int k;
Node *temp = new Node();
cout << "Element " << i+1 <<endl;
cin >> k;
temp->data = k;
temp->next = NULL;
if (i == 0)
{
head = temp;
ptr = temp;
//delete temp;
}
else
{
ptr->next = temp;
ptr = ptr->next;
//delete temp;
}
}
}
void display()
{
//cout <<"Test"<<endl;
Node *temp = head;
while(temp != NULL)
{
cout << temp->data << endl;
temp = temp->next;
}
}
void insert_at_beginning(int x)
{
Node *temp = new Node();
temp->data = x;
temp->next = NULL;
Node *ptr = head;
head = temp;
temp->next = ptr;
}
void insert_(int x, int p)
{
Node *temp = head;
int c = 1;
while((temp != NULL)&&(c != p))
{
temp = temp->next;
c++;
}
Node* temp1 = new Node();
temp1->data = x;
temp1->next = NULL;
temp1->next = temp->next;
temp->next = temp1;
}
void delete_(int p)
{
Node *temp = head;
int c = 1;
while((temp != NULL)&&(c != p))
{
temp = temp->next;
c++;
}
Node *ptr = temp->next;
temp->next = ptr->next;
delete ptr;
}