forked from lugnitdgp/basic_datastructure_programs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
deletion_in_linkedlist.cpp
98 lines (80 loc) · 1.82 KB
/
deletion_in_linkedlist.cpp
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
#include<stdio.h>
#include<malloc.h>
//Declaring a node.
struct Node
{
int data; //data part of node.
struct Node *link; //pointer to next node.
};
struct Node *header; //First Node of list.(global)
//creation of linkedlist
void createlist(int n)
{
struct Node *temp=header;
temp=(struct Node*)malloc(sizeof(struct Node)); //allocating memory to first node.
if(temp==NULL)
printf("Overflow"); //if there is no space in memory
temp->link=NULL;
int i=1;
printf("Enter The Value Of Node%d: ",i);
scanf("%d",&temp->data);
if(header==NULL)
{
temp->link=NULL;
header=temp;
}
i=i+1;
while(i<=n)
{
struct Node* temp1=temp;
temp=(struct Node*)malloc(sizeof(struct Node)); //allocating memory to ith node.
if(temp==NULL)
printf("Overflow");
printf("Enter The Value for Node%d: ",i);
scanf("%d",&temp->data);
temp1->link=temp;
temp->link=NULL;
i=i+1;
}
}
//display of linkedlist
void displaylist()
{
struct Node* temp=header;
printf("\nElements Of List:");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->link;
}
}
//to delete a node
void delete_node(int num,int del)
{
if(del < 1 || num < del)
return;
struct Node* temp = header;
struct Node* prev = header;
for(int i=1; i < del;i++){
prev = temp;
temp = temp->link;
}
if(prev == temp)
header = prev->link;
prev->link = temp->link;
free(temp);
displaylist();
}
//Main Body
int main()
{
int num,del;
printf("Enter The Number Of Nodes For Linkedlist: ");
scanf("%d",&num);
createlist(num);
displaylist();
printf("\nEnter The Node You Want To delete: ");
scanf("%d",&del);
delete_node(num,del);
return 0;
}