-
Notifications
You must be signed in to change notification settings - Fork 0
/
week7-3.c
110 lines (104 loc) · 2.36 KB
/
week7-3.c
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
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node * next;
struct node * prev;
};
struct node * head=NULL;
struct node * tail=NULL;
int n=0;
struct node * newnode(int value){
struct node * temp=(struct node*)malloc(sizeof(struct node));
temp->data=value;
temp->next=NULL;
temp->prev=NULL;
n++;
return temp;
}
void InsertAtBeg(int x){
struct node * temp=newnode(x);
if(head==tail&&head==NULL){
head=tail=temp;
head->next=tail->next=NULL;
head->prev=tail->prev=NULL;
}
else{
temp->next=head;
head->prev=temp;
head=temp;
head->prev=tail;
tail->next=head;
}
}
void InsertAtEnd(int x){
struct node * temp=newnode(x);
if(head==tail&&head==NULL){
head=tail=temp;
head->next=tail->next=NULL;
head->prev=tail->prev=NULL;
}
else{
temp->prev=tail;
temp->next=tail->next;
head->prev=temp;
tail->next=temp;
tail=temp;
}
}
void InsertAtIndex(int index,int x){
struct node * temp=newnode(x);
if(head==tail&&head==NULL){
if(index==0){
head=tail=temp;
head->next=tail->next=NULL;
head->prev=tail->prev=NULL;
}
else{
printf("List is empty!");
}
}
else{
if(index>n-1){
printf("Can't insert at that position!");
}
else{
int i;
struct node * curr=head;
struct node * prevn;
for(i=0;i<n;i++){
prevn=curr;
curr=curr->next;
if(i==index-1){
prevn->next=temp;
temp->prev=prevn;
temp->next=curr;
curr->prev=temp;
break;
}
}
}
}
}
void print(){
if(head==tail&&head==NULL){
printf("List is empty!\n");
}
else{
int i;
struct node * curr=head;
for(i=0;i<n;i++){
printf("%d ",curr->data);
curr=curr->next;
}
}
}
int main(){
InsertAtBeg(3);
InsertAtBeg(2);
InsertAtBeg(1);
InsertAtEnd(4);
InsertAtIndex(2,8);
print();
return 0;
}