public class Link {
private Object data;
public Link next; //注意,这里只是保存一个引用
public Link(Object data) {
this.data=data;
}
public Object peek(){
return data;
}
}
private Object data;
public Link next; //注意,这里只是保存一个引用
public Link(Object data) {
this.data=data;
}
public Object peek(){
return data;
}
}
public class LinkList {
private Link first;
public boolean isEmpty() {
return first==null;
}
public void insertFirst(Object data){ //写数据是写在头
Link link = new Link(data);
link.next=first;
first=link;
}
public Link deleteFirst(){
if(!this.isEmpty()){
Link temp = first;
first = first.next;
return temp;
}else{
return null;
}
}
public void displayList(){
Link current = first;
while(current!=null){
System.out.println(current.peek()+" ");
current = current.next;
}
}
//***********test******************
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.insertFirst("aaa");
linkList.insertFirst("bbb");
System.out.println("del : "+linkList.deleteFirst()+" data:"+linkList.deleteFirst().peek());
linkList.insertFirst("ccc");
linkList.insertFirst("ddd");
linkList.displayList();
}
}
输出:private Link first;
public boolean isEmpty() {
return first==null;
}
public void insertFirst(Object data){ //写数据是写在头
Link link = new Link(data);
link.next=first;
first=link;
}
public Link deleteFirst(){
if(!this.isEmpty()){
Link temp = first;
first = first.next;
return temp;
}else{
return null;
}
}
public void displayList(){
Link current = first;
while(current!=null){
System.out.println(current.peek()+" ");
current = current.next;
}
}
//***********test******************
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.insertFirst("aaa");
linkList.insertFirst("bbb");
System.out.println("del : "+linkList.deleteFirst()+" data:"+linkList.deleteFirst().peek());
linkList.insertFirst("ccc");
linkList.insertFirst("ddd");
linkList.displayList();
}
}
del : dataStructure.link.Link@c17164 data:aaa
ddd
ccc