Skip to content

Commit

Permalink
ronit/linked_list - wap to insert/delete node in linked list
Browse files Browse the repository at this point in the history
Created a function to insert, delete, and traverse the linked list
  • Loading branch information
ronitsrma16 authored Aug 25, 2024
1 parent 8cabe00 commit ce3297d
Showing 1 changed file with 62 additions and 2 deletions.
64 changes: 62 additions & 2 deletions ronit/c/linked_list.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@

/*
Brief - This program is to create a linked list
Here I'm counting Head as 0th index which don't have any value/data
Linked list actual Node counting will start from 1.
*/
#include <stdio.h>
#include <stdlib.h>

Expand All @@ -7,7 +13,11 @@ typedef struct{
}Node;


void print_linkedList(Node *head_pointer);
void print_linkedList(Node *head_pointer);
Node* Insert_Node(Node *Head, int position, int data);
void print_Head(Node *Head_);
Node* Delete_Node(Node *Head, int position);

int main()
{
int run_again = 0;
Expand All @@ -29,7 +39,14 @@ int main()
do{

print_linkedList(Head);

Head = (Node*)Insert_Node(Head, 1, 11);
Head = ( Node*)Insert_Node(Head, 2, 12);
Head = ( Node*)Insert_Node(Head, 3, 13);
Head = ( Node*)Insert_Node(Head, 4, 14);
Head = ( Node*)Insert_Node(Head, 5, 15);
Head = Delete_Node(Head, 3);
printf("Linked List After insertion\r\n");
print_linkedList(Head);
printf("\n");
printf("Do you run program again\r\n");
scanf("%d",&run_again);
Expand All @@ -38,6 +55,49 @@ int main()
return 0;
}

Node* Delete_Node(Node *Head, int position)
{
if(position < 1)
return 0;

Node *tempHead = Head;
int loop = 1;
while(loop != position)
{
tempHead = tempHead->next_address;
loop++;
}
Node *del_node = tempHead->next_address;
tempHead->next_address = del_node->next_address;

return Head;

}

Node* Insert_Node(Node *Head, int position, int data)
{
/* since we count Node positions from 1 */
if(position < 1)
return 0;
Node *newNode = (Node*)malloc(sizeof(Node));
Node *tempHead = Head;


newNode->data = data;
int loop = 1;
while(loop != position)
{
tempHead = (Node*)tempHead->next_address;
loop++;
}

newNode->next_address = tempHead->next_address;
tempHead->next_address = (struct Node*)newNode;


return Head;
}

// Traversal Of the Nodes
void print_linkedList(Node *head_pointer)
{
Expand Down

0 comments on commit ce3297d

Please sign in to comment.