-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path62insertAtPos.c
More file actions
108 lines (100 loc) · 1.96 KB
/
62insertAtPos.c
File metadata and controls
108 lines (100 loc) · 1.96 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
98
99
100
101
102
103
104
105
106
107
108
#include<stdio.h>
#include<stdlib.h>
struct node{
struct node* prev;
int data;
struct node* next;
};
int insertFirst(struct node**,int);
struct node* newNode(int);
void display(struct node**);
int insertLast(struct node**,int);
int insertAtPos(struct node**,int,int);
int main(){
struct node* head=NULL;
int itr1=0,num,no,pos;
printf("How many nodes to be created.\n");
scanf("%d",&num);
for(itr1=0;itr1<num;itr1++){
printf("Element no. %d :",itr1+1);
scanf("%d",&no);
insertLast(&head,no);
}
display(&head);
printf("Insert the pos followed by element.\n");
scanf("%d %d",&pos,&no);
insertAtPos(&head,no,pos);
display(&head);
return 0;
}
int insertAtPos(struct node** Head,int no,int pos){
struct node * temp=*Head;
struct node * tNew=NULL;
if(*Head==NULL){
printf("List is empty.\n");
return -1;
}
if(pos==1){
insertFirst(Head,no);
}else{
while(pos-1>1){
temp=temp->next;
pos--;
}
tNew=newNode(no);
tNew->next=temp->next;
tNew->prev=temp;
tNew->next->prev=tNew;
temp->next=tNew;
}
}
int insertLast(struct node** Head,int no){
struct node *temp=*Head;
if(*Head==NULL){
temp=newNode(no);
*Head=temp;
}else{
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=newNode(no);
temp->next->prev=temp;
}
}
int insertFirst(struct node** Head,int no){
struct node* temp=NULL;
if(*Head==NULL){
temp=newNode(no);
*Head=temp;
}else{
temp=newNode(no);
temp->prev=NULL;
temp->next=*Head;
temp->next->prev=temp;
*Head=temp;
}
}
struct node* newNode(int no){
struct node *temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL){
printf("Was not able to allocate memory.\n");
return 0;
}
temp->prev=NULL;
temp->next=NULL;
temp->data=no;
return temp;
}
void display(struct node** Head){
struct node *temp=*Head;
if(*Head==NULL){
printf("Nothing to display.\n");
return;
}else{
while(temp->next!=NULL){
printf("|%d|<=>",temp->data);
temp=temp->next;
}
printf("|%d|\n",temp->data);
}
}