LinkList的java实现
单链表的类
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
操作类
package Chapter2;
import java.util.Scanner;
public class ListNodeOperation {
public static void printListNode(ListNode end){
while(end.next != null){
System.out.print(end.val+"->");
end=end.next;
}
System.out.println(end.val);
}
public static ListNode createListNode(){
Scanner in=new Scanner(System.in);
ListNode end=new ListNode(in.nextInt());
while(in.hasNext()){
String nextString=in.next();
if(nextString.equals("quit")){
break;
}
ListNode n=new ListNode(Integer.parseInt(nextString));
n.next=end;
end=n;
}
return end;
}
}
测试输出:
public static void main(String[] args){
Scanner in=new Scanner(System.in);
ListNode end=new ListNode(in.nextInt());
while(in.hasNext()){
String nextString=in.next();
if(nextString.equals("quit")){
break;
}
ListNode n=new ListNode(Integer.parseInt(nextString));
n.next=end;
end=n;
}
ListNodeOperation.printListNode(end);
}