-
Notifications
You must be signed in to change notification settings - Fork 0
/
LL1.cpp
136 lines (129 loc) · 2.59 KB
/
LL1.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *create(int n)
{
// int value;
// struct node *head, *p;
// head = (struct node *)malloc(sizeof(struct node));
// cout << "1st element" << endl;
// cin >> value;
// head->data = value;
// head->next = NULL;
// p = head;
// for (int i = 1; i < n; i++)
// {
// p->next = (struct node *)malloc(sizeof(struct node));
// p = p->next;
// cin >> p->data;
// p->next = NULL;
// }
// return head;
struct node *p = (struct node *)malloc(sizeof(struct node));
p->data = n;
p->next = NULL;
return p;
};
void display(struct node *head)
{
struct node *p = head;
while (p != NULL)
{
cout << p->data << endl;
p = p->next;
}
};
struct node *insert(struct node *head, int val, int loc)
{
struct node *p, *q;
q = (struct node *)malloc(sizeof(struct node *));
q->data = val;
q->next = NULL;
if (loc == 1)
{
q->next = head;
head = q;
return head;
}
else
{
p = head;
for (int i = 1; i < loc - 1; i++)
{
p = p->next;
if (p == NULL)
{
return head;
}
}
q->next = p->next;
p->next = q;
return head;
}
return head;
}
struct node *delete1(struct node *head, int val, int loc)
{
if (head == NULL)
{
return head;
}
struct node *p = head, *q;
if (loc == 1)
{
head = head->next;
free(p);
}
while (p->data != val)
{
q = p;
p = p->next;
}
if (p == NULL)
{
return head;
}
q = p->next;
p->next = q->next;
free(q);
return head;
};
struct node *reverse(struct node *head)
{
if (head == NULL)
{
return NULL;
}
struct node *prev = nullptr;
struct node *current = head;
struct node *next = nullptr;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
return head;
};
int main()
{
int n;
struct node *head;
cin >> n;
head = create(n);
display(head);
head = insert(head, 99, 3);
display(head);
// head = reverse(head);
// display(head);
head = delete1(head, 99, 3);
display(head);
return 0;
}