class Node {
public int data;
public Node next;
public Node ( int data) {
this . data = data;
}
}
public class SingleList {
public Node head;
public void addFirst ( int data) {
Node node = new Node ( data) ;
if ( this . head == null) {
this . head = node;
return ;
} else {
node. next = this . head;
this . head = node;
}
}
public void show ( ) {
Node cur= this . head;
while ( cur!= null) {
System. out. print ( cur. data+ " " ) ;
cur= cur. next;
}
System. out. println ( ) ;
}
public Node moveK ( int k) {
Node fast= this . head;
Node slow= this . head;
if ( k<= 0 || this . head== null) {
return null;
}
while ( k- 1 > 0 ) {
if ( fast. next != null) {
fast = fast. next;
k-- ;
} else {
System. out. println ( "没有这个节点 " ) ;
return null;
}
}
while ( fast. next!= null) {
fast= fast. next;
slow= slow. next;
}
return slow;
}
}
public class TestDemo {
public static void main ( String[ ] args) {
SingleList singleList= new SingleList ( ) ;
singleList. addFirst ( 2 ) ;
singleList. addFirst ( 1 ) ;
singleList. addFirst ( 3 ) ;
singleList. addFirst ( 4 ) ;
singleList. addFirst ( 2 ) ;
singleList. show ( ) ;
Node ret= singleList. moveK ( 4 ) ;
System. out. println ( ret. data) ;
}
}