fulls source code for insertion and deletion in singly linked list

fulls source code for insertion and deletion in singly linked list in c
This commit is contained in:
Rupeshiya 2018-01-27 22:47:42 +05:30 committed by GitHub
parent 2d376fb740
commit ebc7892f01
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,65 +3,96 @@
function can be modified according to the data type, easily. function can be modified according to the data type, easily.
deleteNode deletes a node when passed with a key of the node. deleteNode deletes a node when passed with a key of the node.
*/ */
#include <stdio.h> #include<stdio.h>
#include <stdlib.h> struct node
{int info;
struct Node struct node *link;
{
int data;
struct Node *next;
}; };
struct node *start=NULL;
void push(struct Node** head_ref, int new_data) ///////////////////////////////////////////////////////////
struct node * createnode()//function to create node
{ {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); struct node *t;
new_node->data = new_data; t=(struct node*)malloc(sizeof(struct node));
new_node->next = (*head_ref); return(t);
(*head_ref) = new_node;
} }
////////////////////////////////////////////////////////
void deleteNode(struct Node **head_ref, int key) void insert()//function to insert at first location
{ {
struct Node* temp = *head_ref, *prev; struct node *p;
p=createnode();
if (temp != NULL && temp->data == key) printf("\nenter the number to insert");
{ scanf("%d",&p->info);
*head_ref = temp->next; p->link=NULL;
free(temp); if(start==NULL)
return; {
} start=p;
}
else
while (temp != NULL && temp->data != key) {
{ p->link=start;
prev = temp; start=p;
temp = temp->next; }
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
} }
///////////////////////////////////////////////////////////
void printList(struct Node *node) void deleteion()//function to delete from first position
{ {
while (node != NULL) struct node *t;
if(start==NULL)
{ {
printf(" %d ", node->data); printf("\nlist is empty");
node = node->next; }
else
{
struct node *p;
p=start;
start=start->link;
free(p);
} }
} }
///////////////////////////////////////////////////////
void viewlist()//function to display values
{
struct node *p;
if(start==NULL)
{
printf("\nlist is empty");
}
else
{ p=start;
while(p!=NULL)
{
printf("%d ",p->info);
p=p->link;
}
}
}
//////////////////////////////////////////////////////////////////////
int main() int main()
{ {
/* new node can be created here as :- int n;
struct Node* head = NULL; while(1)
push(&head, data); {
printf("\n1.add value at first location");
and a node can be delete by using printf("\n2.delete value from first location");
deleteNode(&head, key); printf("\n3.view value");
*/ printf("\nenter your choice");
return 0; scanf("%d",&n);
switch(n)
{
case 1:
insert();
break;
case 2:
deleteion();
break;
case 3:
viewlist();
break;
default:
printf("\ninvalid choice");
}
}
return(0);
} }