-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path42insertLast.c
94 lines (87 loc) · 1.77 KB
/
42insertLast.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>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node* newNode(int no);
int insertLast(struct node **head,int);
int createNode(struct node **);
void display(struct node**);
int insertFirst(struct node **head,struct node **tail,int);
int main(){
int data;
struct node *head=NULL;
createNode(&head);
display(&head);
struct node *tail=head;
while(tail->next!=head){
tail=tail->next;
}
printf("\nInsert an element at first place.\n");
scanf("%d",&data);
insertFirst(&head,&tail,data);
display(&head);
return 0;
}
int insertFirst(struct node **head,struct node **tail,int no){
struct node *temp=*head;
struct node *newN=NULL;
if(*head==NULL){
newN=newNode(no);
*head=newN;
newN->next=*head;
}else{
newN=newNode(no);
newN->next=*head;
*head=newN;
(*tail)->next= *head;
}
return 0;
}
int createNode(struct node **head){
int itr1,data,num;
printf("How many nodes to be created.\n");
scanf("%d",&num);
for(itr1=0;itr1<num;itr1++){
printf("Enter element no. %d : ",itr1+1);
scanf("%d",&data);
insertLast(head,data);
}
}
int insertLast(struct node **head,int no){
struct node *temp=*head;
struct node *newN=NULL;
if(*head==NULL){
newN=newNode(no);
*head=newN;
newN->next=*head;
}else{
while(temp->next!=*head){
temp=temp->next;
}
newN=newNode(no);
temp->next=newN;
newN->next=*head;
}
return 0;
}
struct node* newNode(int no){
struct node *new=(struct node*)malloc(sizeof(struct node));
if(new==NULL){
printf("Memory allocation failed.\n");
exit(1);
}
new->data=no;
new->next=NULL;
return new;
}
void display(struct node **head){
struct node *temp=*head;
printf("\n\nOUTPUT:\n");
while(temp->next!=*head){
printf("|%d|->",temp->data);
temp=temp->next;
}
printf("|%d|\n",temp->data);
}