-
Notifications
You must be signed in to change notification settings - Fork 0
/
(LINKEDLISTdetectaloopinlinkedlist.cpp
113 lines (102 loc) · 1.84 KB
/
(LINKEDLISTdetectaloopinlinkedlist.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
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;
void create(struct node * );
void display(struct node * );
void reverseanddisplay(struct node *);
void findmid(struct node *);
int main()
{
int ch;
while(1)
{
printf("\nPress 1:Create 2:Display 0:Exit 3:reverse and display 4.Find middle element\n ");
printf("enter your choice=");
scanf("%d",&ch);
switch(ch)
{
case 1: create(head); break;
case 2: display(head);break;
case 3: reverseanddisplay(head);
break;
case 4: findmid(head);break;
case 0: exit(0);
default: printf("Wrong choice....use only above option ");
}
}
return 0;
}
void findmid(struct node *head){
struct node *p=head;
int c=0;
while(p!=NULL){
c++;
p=p->next;
}
c/=2;
if(c%2==0){
int x=1;
struct node *q=head;
while(x!=c){
q=q->next;
x++;
}
printf("Middle elements are : %d and %d",q->data,q->next->data);
}
else{
int x=1;
struct node *q=head;
while(x!=c){
q=q->next;
x++;
}
printf("Middle element is : %d ",q->data);
}
}
void reverseanddisplay(struct node* head)
{
if(head==NULL)
{
return;
}
reverseanddisplay(head->next);
printf("%d->",head->data);
}
void create(struct node *ptr)
{
struct node *temp;
int x;
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&x);
temp->data=x;
temp->next=NULL;
if(head==NULL)
head=temp;
else
{
ptr=head;
while( ptr->next!=NULL )
{
ptr=ptr->next;
}
ptr->next=temp;
}
}
void display(struct node *ptr)
{
if(ptr==NULL) printf("Empty List");
else
{ printf("\nLinked list is :\n");
while(ptr!=NULL)
{
printf("%d->",ptr->data);
ptr=ptr->next;
}
}
}