-
Notifications
You must be signed in to change notification settings - Fork 0
/
LL2.cpp
91 lines (88 loc) · 1.78 KB
/
LL2.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
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int data;
struct node *prev, *next;
};
struct node *create(int data)
{
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode->prev = NULL;
newnode->next = NULL;
newnode->data = data;
return newnode;
};
struct node *insert(struct node *head, int data, int loc)
{
if (head == NULL)
{
head = create(data);
return head;
}
else
{
struct node *p = head, *q = create(data);
for (int i = 1; i < loc - 1 && p->next != NULL; i++)
{
p = p->next;
}
q->next = p->next;
if (p->next != NULL)
{
p->next->prev = q;
}
p->next = q;
q->prev = p;
}
return head;
}
struct node *display(struct node *head)
{
struct node *p = head;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
return head;
};
struct node *delete1(struct node *head, int loc)
{
struct node *p = head, *q = nullptr;
if (loc == 1)
{
head = p->next;
head = head->prev;
free(p);
return head;
}
else
{
for (int i = 1; i < loc; i++)
{
q = p;
p = p->next;
}
q->next = p->next;
p->next->prev = q;
free(p);
return head;
}
};
int main()
{
struct node *head = NULL;
head = create(10);
head = insert(head, 20, 2);
head = insert(head, 30, 3);
head = insert(head, 99, 4);
display(head);
// head = reverse(head);
// display(head);
head = delete1(head, 2);
display(head);
return 0;
}