Update delete-the-Kth-node-from-the-end.java

pull/780/head
Aditya Yaduvanshi 2022-08-07 01:38:00 +05:30 committed by GitHub
parent 8b5f1dc1ad
commit 9724d09396
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 19 deletions

View File

@ -1,11 +1,4 @@
/* Given a linked list consisting of N nodes and an integer K, your task is to delete the Kth node from the end of the linked
list */
// Time Complexity: O(n).
// Space complexity: O(1).
import java.util.*;
import java.io.*;
class LinkedList class LinkedList
{ {
@ -27,10 +20,14 @@ import java.util.*;
head = new_node; head = new_node;
} }
//this function will delete the kth node in list
void deleteNode(int position) void deleteNode(int position)
{ {
//if linked list is empty then return
if (head == null) if (head == null)
return; return;
Node temp = head; Node temp = head;
if (position == 0) if (position == 0)
{ {
@ -57,23 +54,20 @@ import java.util.*;
} }
public static void main(String[] args) public static void main(String[] args)
{ {
Scanner sc = new Scanner(System.in); LinkedList k_List = new LinkedList();
int t= sc.nextInt(); k_List.addNode(1);
while(t-- >0 ){ k_List.addNode(2);
int n = sc.nextInt(); k_List.addNode(3);
int k = sc.nextInt(); k_List.addNode(4);
LinkedList llist = new LinkedList(); k_List.addNode(5);
int p[]=new int[n]; k_List.addNode(6);
for(int i=0;i<n;i++)
{
p[i] = sc.nextInt();
}
for(int i=n-1;i>=0;i--) for(int i=n-1;i>=0;i--)
{ {
llist.push(p[i]); llist.push(p[i]);
} }
//this will delete the kth node
llist.deleteNode(k-1); llist.deleteNode(k-1);
//this will print the linked list after deleteion
llist.printList(); } llist.printList(); }
} }
} }