-
Notifications
You must be signed in to change notification settings - Fork 3
/
addAtRandom.c
94 lines (79 loc) · 1.57 KB
/
addAtRandom.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
#include <stdio.h>
int count;
struct node
{
int data;
struct node *next;
};
struct node *head,*newNode,*temp;
void Addnode_atRandom() // function to add a node in the given position
{
int dataNode;
int pos;
printf("Enter the number to be added: ");
scanf("%d",&dataNode);
printf("Enter the position to be inserted: ");
scanf("%d",&pos);
pos=pos-1;
if(pos<count)
{
newNode=(struct node*)malloc(sizeof(struct node));
newNode->data=dataNode;
int i=1;
temp=head;
while(i<pos)
{
temp=temp->next;
i++;
}
newNode->next = temp->next;
temp->next=newNode;
}
else
{
printf("Invalid Input!!");
}
}
int main()
{
int choice;
head = 0;
do
{
newNode=(struct node*)malloc(sizeof(struct node)); // creating a new node
printf("Enter the number: ");
scanf("%d",&newNode->data); //reading a data
newNode->next=0;
if(head==0)
{
head=temp=newNode;
}
else
{
temp->next=newNode;
temp=newNode;
}
printf("Do You wish to add a new element?\n\nyes - 1\nno - 0\n\n");
scanf("%d",&choice);
}while(choice==1); // iterating using a "do while" to add more data
printf("The list Entered: ");
temp=head;
count=0;
do
{
printf("%d ",temp->data);
temp=temp->next;
count++;
} while(temp->next!=0);
printf("\n\n");
Addnode_atRandom(); // function call
printf("The list Now: ");
temp=head;
count=0;
do
{
printf("%d ",temp->data);
temp=temp->next;
count++;
} while(temp->next!=0);
}