You are on page 1of 2

8/22/23, 1:29 AM insertionatanypos.

insertionatanypos.c

1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct node {
5 int data;
6 struct node *next;
7 };
8
9 void main() {
10 struct node *head;
11 struct node *newnode;
12 struct node *temp;
13 head = NULL;
14
15 int choice = 1, count = 0;
16
17 while (choice) {
18 newnode = (struct node *)malloc(sizeof(struct node));
19 printf("Enter Data:\n");
20 scanf("%d", &newnode->data);
21 newnode->next = NULL;
22
23 if (head == NULL) {
24 head = temp = newnode;
25 } else {
26 temp->next = newnode;
27 temp = newnode;
28 }
29
30 printf("Do you want to continue (0, 1)?\n");
31 scanf("%d", &choice);
32 }
33
34 printf("--------------------------------\n");
35
36 temp = head;
37 while (temp != NULL) {
38 printf("\n%d\n", temp->data);
39 temp = temp->next;
40 count++;
41 }
42 printf("\nCount=%d \n", count);
43
44 int pos, i = 1;
45
46 struct node *anynode;
47 anynode = (struct node *)malloc(sizeof(struct node));
48
49 //finding position
50 printf("Enter the position: ");
51 scanf("%d", &pos);
52 if (pos > count){
53 printf("Invalid position\n");
54 }
55 else{
56 temp = head;

localhost:64626/a7ed0b3f-20ed-425d-b94f-2a8cfff7de34/ 1/2
8/22/23, 1:29 AM insertionatanypos.c

57 while (i < pos)


58 {
59 temp = temp->next;
60 i++;
61 }
62
63 printf("Enter Data: ");
64
65 //data
66 scanf("%d", &anynode->data);
67
68 //right link
69 anynode->next = temp->next;
70
71 //left link
72 temp->next = anynode;
73 }
74
75 //print
76 temp = head;
77 count=0;
78 while (temp != NULL) {
79 printf("\n%d\n", temp->data);
80 temp = temp->next;
81 count++;
82 }
83 printf("\nCount=%d \n", count);
84 }
85  

localhost:64626/a7ed0b3f-20ed-425d-b94f-2a8cfff7de34/ 2/2

You might also like