Skip to content

Commit 8a517fc

Browse files
authored
Deleting node by position from singly Linked List
1 parent 8543834 commit 8a517fc

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// A complete working C program to delete a node in a linked list
2+
// at a given position
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
6+
// A linked list node
7+
struct Node
8+
{
9+
int data;
10+
struct Node *next;
11+
};
12+
13+
/* Given a reference (pointer to pointer) to the head of a list
14+
and an int, inserts a new node on the front of the list. */
15+
void push(struct Node** head_ref, int new_data)
16+
{
17+
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
18+
new_node->data = new_data;
19+
new_node->next = (*head_ref);
20+
(*head_ref) = new_node;
21+
}
22+
23+
/* Given a reference (pointer to pointer) to the head of a list
24+
and a position, deletes the node at the given position */
25+
void deleteNode(struct Node **head_ref, int position)
26+
{
27+
// If linked list is empty
28+
if (*head_ref == NULL)
29+
return;
30+
31+
// Store head node
32+
struct Node* temp = *head_ref;
33+
34+
// If head needs to be removed
35+
if (position == 0)
36+
{
37+
*head_ref = temp->next; // Change head
38+
free(temp); // free old head
39+
return;
40+
}
41+
42+
// Find previous node of the node to be deleted
43+
for (int i=0; temp!=NULL && i<position-1; i++)
44+
temp = temp->next;
45+
46+
// If position is more than number of ndoes
47+
if (temp == NULL || temp->next == NULL)
48+
return;
49+
50+
// Node temp->next is the node to be deleted
51+
// Store pointer to the next of node to be deleted
52+
struct Node *next = temp->next->next;
53+
54+
// Unlink the node from linked list
55+
free(temp->next); // Free memory
56+
57+
temp->next = next; // Unlink the deleted node from list
58+
}
59+
60+
// This function prints contents of linked list starting from
61+
// the given node
62+
void printList(struct Node *node)
63+
{
64+
while (node != NULL)
65+
{
66+
printf(" %d ", node->data);
67+
node = node->next;
68+
}
69+
}
70+
71+
/* Drier program to test above functions*/
72+
int main()
73+
{
74+
/* Start with the empty list */
75+
struct Node* head = NULL;
76+
77+
push(&head, 7);
78+
push(&head, 1);
79+
push(&head, 3);
80+
push(&head, 2);
81+
push(&head, 8);
82+
83+
puts("Created Linked List: ");
84+
printList(head);
85+
deleteNode(&head, 4);
86+
puts("\nLinked List after Deletion at position 4: ");
87+
printList(head);
88+
return 0;
89+
}

0 commit comments

Comments
 (0)