Skip to content

Instantly share code, notes, and snippets.

@pratik7368patil
Created July 3, 2020 07:21
Show Gist options
  • Save pratik7368patil/0f556e9077175a04c98e2dbfb680527e to your computer and use it in GitHub Desktop.
Save pratik7368patil/0f556e9077175a04c98e2dbfb680527e to your computer and use it in GitHub Desktop.
Search Last Kth node in Linked List
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class Main {
public static void main(String[] args) {
Node head = new Node(1);
insertLast(head, 2);
insertLast(head, 3);
insertLast(head, 5);
head = insertFirst(head, 0);
insertMiddle(head, 4, 4);
head = insertFirst(head, -1);
insertMiddle(head, 6, 6);
System.out.println("Search Res. : " + searchKLast(head, 5));
//display(head);
}
// this is the function your looking for
public static int searchKLast(Node head, int K) {
Node fast = head; // fast pointer
Node slow = head; // slow pointer
while(K > 0) {
fast = fast.next; // move fast pointer forward
K--;
}
while(fast!=null) {
fast = fast.next;
slow = slow.next;
}
return slow.data; // return data of last k'th node
}
public static void insertMiddle(Node head, int val, int position) {
Node newNode = new Node(val);
Node temp = head;
while(temp.next != null && position > 1) {
position--;
temp = temp.next;
}
Node help = temp.next;
newNode.next = help;
temp.next = newNode;
}
public static Node insertFirst(Node head, int val) {
Node newNode = new Node(val);
newNode.next = head;
return newNode;
}
public static void insertLast(Node head, int val) {
Node newNode = new Node(val);
Node temp = head;
while(temp.next!=null) {
temp = temp.next;
}
temp.next = newNode;
}
public static void display(Node head) {
Node temp = head;
while(temp!=null){
System.out.println(temp.data);
temp = temp.next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment