-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion.c
More file actions
97 lines (87 loc) · 1.81 KB
/
insertion.c
File metadata and controls
97 lines (87 loc) · 1.81 KB
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
#include <stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node *head;
void traversal(){
struct Node *ptr=head;
while(ptr!=NULL){
printf("%d\t",ptr->data);
ptr=ptr->next;
}
}
// Insert At First
void insertAtFirst(int data){
struct Node *p=(struct Node*)malloc(sizeof(struct Node));
p->data=data;
p->next=NULL;
p->next=head;
head=p;
}
// Insert At Any position
void insertAnyPosition(int data){
int x;
printf("Insert at position");
scanf("%d",&x);
int count=1;
struct Node *newnode=(struct Node*)malloc(sizeof(struct Node));
struct Node *p=head;
newnode->next=NULL;
newnode->data=data;
if(x==1){
newnode->next=head;
head=newnode;
}else{
struct Node *current=head;
while(count<x-1){
current=current->next;
count++;
}
newnode->next=current->next;
current->next=newnode;
}
}
// insertAtLast
void insertAtLast(int data){
struct Node *newnode=(struct Node*)malloc(sizeof(struct Node));
struct Node *p=head;
newnode->data=data;
while(p->next!=NULL){
p=p->next;
}
p->next=newnode;
newnode->next=NULL;
}
int main()
{
int n,x;
struct Node *newNode,*temp;
head=NULL;
int i=0;
scanf("%d",&n);
while(i<n){
newNode=(struct Node*)malloc(sizeof(struct Node));
printf("Enter Data :");
scanf("%d",&newNode->data);
newNode->next=NULL;
if(head==NULL){
head=temp=newNode;
}else{
temp->next=newNode;
temp=newNode;
}
i++;
}
traversal();
insertAtFirst(45);
insertAnyPosition(100);
insertAtLast(999);
printf("\n");
traversal();
insertAtFirst(45);
printf("\n");
traversal();
return 0;
}