w3resource

C Exercises: Remove Nth node from the end of a singly linked list

C Singly Linked List : Exercise-28 with Solution

Write a C program to remove the Nth node from the end of a singly linked list.

Sample Solution:

C Code:

#include<stdio.h>
#include <stdlib.h>


struct Node {
    int data;
    struct Node* next;
};

// Function to create a new node
struct Node* newNode(int data) {
    struct Node* node = (struct Node*) malloc(sizeof(struct Node));
    node->data = data;
    node->next = NULL;
    return node;
}

void remove_Nth_From_End(struct Node* head, int n){
    struct Node *temp = head;
    int len = 0;
    while(temp != NULL){
        temp = temp->next;
        len++;
    }
    if(len < n){
        return;
    }
    temp = head;
    for(int i = 1; i < len-n; i++){
        temp = temp->next;
    }
    if(temp->next == NULL){
        head = head->next;
        return;
    }
    struct Node *temp2 = temp->next;
    temp->next = temp2->next;
    free(temp2);
}
// Function to print a linked list
void displayList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
	struct Node* head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = newNode(5);
    printf("Original Singly List:\n");
	displayList(head);
	printf("\nRemove 1st node from the end of a singly linked list:\n");
	remove_Nth_From_End(head, 1);
	displayList(head);
	printf("\nRemove 3rd node from the end of a singly linked list:\n");
	remove_Nth_From_End(head, 3);
	displayList(head);
    return 0;
}

Sample Output:

Original Singly List:
1 2 3 4 5 

Remove 1st node from the end of a singly linked list:
1 2 3 4 

Remove 3rd node from the end of a singly linked list:
1 3 4 

Flowchart :

Flowchart: Remove Nth node from the end of a singly linked list.
Flowchart: Remove Nth node from the end of a singly linked list.

C Programming Code Editor:

Previous: Implement a binary tree using linked list representation.
Next: Combine k sorted linked lists into a single sorted linked list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.