Write a program to Remove Nth Node From End of List
Example 1:
Input: 5->2->8->4->1->NULL, n=3
Output:5->2->4->1->NULL
Approach:
Java
public class LinkListDeletionNthFEnd {public static void main(String[] args) {ListNode l = new ListNode(1);l.next = new ListNode(2);l.next.next = new ListNode(3);l.next.next.next = new ListNode(4);l.next.next.next.next = new ListNode(5);int n = 5;int length = linkedListLength(l);ListNode node = removetNthNodeFromEnd(l, n, length);System.out.println("After Removing :");linkedListTraversal(node);}private static void linkedListTraversal(ListNode node) {while (node != null) {System.out.print(node.val + " ");node = node.next;}}private static int linkedListLength(ListNode node) {int length = 0;while (node != null) {node = node.next;length++;}return length;}public static ListNode removetNthNodeFromEnd(ListNode head, int n, int length) {// If list is nullif (head == null || n == 0) {return head;}// if delete first element// Base caseif (n == length) {return head.next;}int count = 0;ListNode root = head;ListNode prev = head;while (root != null) {count++;// if found nth then deleteif (count == length - n + 1) {prev.next = root.next;break;}// change previousprev = root;// head->nextroot = root.next;}return head;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}// Time Complexity : O(n)// Space Complexity : O(1)
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//function to traverse(print) a linked//listvoid linkedListTraversal(Node *head){Node *temp=head;//iterate till we reach end of the linked//listwhile(temp!=NULL){//print the current//node datacout<<temp->data<<" ";//move to next nodetemp=temp->next;}}//function to find the length of//inked listint linkedListLength(Node* node){int length = 0;while (node !=NULL) {node = node->next;length++;}return length;}//function to remove nth node//from end of listNode* removetNthNodeFromEnd(Node* head, int n, int length){// If list is empty or n=0if (head ==NULL || n == 0) {return head;}// if delete first element// Base caseif (n == length) {return head->next;}int count = 0;Node* root = head;Node* prev = head;while (root !=NULL) {count++;// if found nth then deleteif (count == length - n + 1) {prev->next = root->next;free(root);break;}// change previousprev = root;// head->nextroot = root->next;}return head;}int main(){Node *head=new Node(5);head->next=new Node(2);head->next->next=new Node(8);head->next->next->next=new Node(4);head->next->next->next->next=new Node(1);int length=linkedListLength(head);int n=3;head=removetNthNodeFromEnd(head,n,length);cout<<"After Removing \n";linkedListTraversal(head);return 0;}// Time Complexity : O(n)// Space Complexity : O(1)
No comments:
Post a Comment