Skip to content

Instantly share code, notes, and snippets.

@astkaasa
Created March 18, 2013 00:47
Show Gist options
  • Save astkaasa/5184329 to your computer and use it in GitHub Desktop.
Save astkaasa/5184329 to your computer and use it in GitHub Desktop.
public class KthToLast {
public static void main( String[] args ) {
LinkNode head = new LinkNode( 1 );
head.append( new LinkNode( 10 ) );
head.append( new LinkNode( 18 ) );
head.append( new LinkNode( 5 ) );
head.append( new LinkNode( 9 ) );
head.append( new LinkNode( 100 ) );
head.append( new LinkNode( 20 ) );
head.append( new LinkNode( 30 ) );
head.append( new LinkNode( 70 ) );
printLinkedList( head );
System.out.println( "The 7th to last element of this list is: " );
//assume that the link list only has elements greater than 0
System.out.println( FindKthToLast( head, 7 ) );
}
public static void printLinkedList( LinkNode head ) {
while ( head != null ) {
System.out.print( head.getValue() );
System.out.print( "->" );
head = head.getNext();
}
System.out.println( "null" );
}
public static int FindKthToLast( LinkNode head, int k ) {
LinkNode p1 = head;
for ( int i = 1; i <= k; i++ ) {
if ( p1 != null )
p1 = p1.getNext();
//if k is larger than the list length, return 0 (This is an impossible value for my assumption.)
else return 0;
}
LinkNode p2 = head;
while ( p1!= null ) {
p1 = p1.getNext();
p2 = p2.getNext();
}
return p2.getValue();
}
}
public class LinkNode {
private int value;
private LinkNode next;
public LinkNode( int val ) {
this.value = val;
this.next = null;
}
public int getValue() {
return value;
}
public void setValue( int value ) {
this.value = value;
}
public LinkNode getNext() {
return next;
}
public void setNext( LinkNode n ) {
this.next = n;
}
public void append( LinkNode n ) {
LinkNode currNode = this;
while ( currNode.next != null ) {
currNode = currNode.next;
}
currNode.next = n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment