Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Find kth element from last in a singly linked list
/** * Given a singly linked list, find kth element from last. * * @author: Jayesh Chandrapal */ import java.util.*; import java.lang.*; class Node { int data; Node next; Node(int data, Node next) { this.data = data; this.next = next; } } class Rextester { public static void main(String args[]) { Node mylist = new Node(10, new Node(20, new Node(30, new Node(40, new Node(50, new Node(60, new Node(70, null))))))); int k = 2; Node kth = getElementFromLast(mylist, k); if(kth != null) { System.out.format("\n%dth element from last = %d\n", k, kth.data); } else { System.out.println("Incorrect index entered!"); } } public static Node getElementFromLast(Node head, int k) { if(k < 0) { return null; } Node current = head; Node kth = head; int index = 0; while(current != null) { if(index >= k) { kth = kth.next; } current = current.next; index++; } if(index < k) return null; return kth; } }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
Palindrome String Checking
Sort an array of 0's 1's 2's 3 pointer approach
bubble sort
pk2
Rabbits in forest (leetod)
Leetcode 297. Serialize and Deserialize Binary Tree
asdasd
Sumod
Central Inteligence Agency
jb11.0 threads tick tock 1.0
Please log in to post a comment.