File tree Expand file tree Collapse file tree 1 file changed +136
-0
lines changed
Expand file tree Collapse file tree 1 file changed +136
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < iostream>
2+ #include < stdlib.h>
3+ using namespace std ;
4+
5+ struct node
6+ {
7+ int data;
8+ struct node *next;
9+ struct node *prv;
10+ };
11+
12+ void create (struct node **h)
13+ {
14+ int n,i;
15+ printf (" How many elements you want to enter: " );
16+ scanf (" %d" ,&n);
17+ struct node *ptr=NULL ;
18+ for (i=0 ;i<n;i++)
19+ {
20+ struct node *cur=(struct node *)malloc (sizeof (struct node ));
21+ cur->data =rand ()%10 ;
22+ cur->next =NULL ;
23+ cur->prv =NULL ;
24+
25+ if (*h==NULL )
26+ {
27+ *h=cur;
28+ cur->next =cur->prv =cur;
29+ ptr=cur;
30+ }
31+ else
32+ {
33+ cur->prv =ptr;
34+ ptr->next =cur;
35+ cur->next =*h;
36+ ptr=cur;
37+ }
38+ }
39+
40+ }
41+
42+ void display (struct node *h)
43+ {
44+ struct node *cur;
45+ printf (" linked list:\t " );
46+ for (cur=h;cur->next !=h;cur=cur->next )
47+ {
48+ printf (" %d\t " ,cur->data );
49+ }
50+ printf (" %d" ,cur->data );
51+ }
52+
53+ void insert (struct node **h,int x,int p)
54+ {
55+ struct node *cur;
56+ struct node *ptr;
57+ cur=(struct node *)malloc (sizeof (struct node ));
58+ cur->data =x;
59+ cur->next =cur->prv =NULL ;
60+
61+ if (*h==NULL )
62+ {
63+ *h=cur;
64+ cur->next =cur->prv =cur;
65+ }
66+ else if (p==0 )
67+ {
68+ cur->next =*h;
69+ cur->prv =(*h)->prv ;
70+ (*h)->prv ->next =cur;
71+ (*h)->prv =cur;
72+ *h=cur;
73+ }
74+ else
75+ {
76+ ptr=*h;
77+ int i=1 ;
78+ while (i<p && ptr->next !=*h)
79+ {
80+ ptr=ptr->next ;
81+ i++;
82+ }
83+ cur->next =ptr->next ;
84+ cur->prv =ptr;
85+ ptr->next ->prv =cur;
86+ ptr->next =cur;
87+ }
88+
89+ }
90+
91+ void del (struct node **h,int p)
92+ {
93+ struct node *ptr;
94+ struct node *cur;
95+ if (*h==NULL )
96+ {
97+ printf (" EMPTY" );
98+ }
99+ else if (p==0 )
100+ {
101+ for (ptr=*h;ptr->next !=*h;ptr=ptr->next ){}
102+
103+ ptr->next =(*h)->next ;
104+ cur=*h;
105+ *h=(*h)->next ;
106+ (*h)->next ->prv =ptr;
107+ free (cur);
108+ }
109+ else
110+ {
111+ ptr=*h;
112+ int i=1 ;
113+ while (i<p && ptr->next !=*h)
114+ {
115+ cur=ptr;
116+ ptr=ptr->next ;
117+ i++;
118+ }
119+ cur->next =ptr->next ;
120+ ptr->next ->prv =cur;
121+ free (ptr);
122+ }
123+ }
124+
125+ int main ()
126+ {
127+ struct node *head=NULL ;
128+ create (&head);
129+ display (head);
130+ insert (&head,2 ,6 );
131+ display (head);
132+ printf (" \n " );
133+ del (&head,0 );
134+ display (head);
135+ return 0 ;
136+ }
You can’t perform that action at this time.
0 commit comments