链表:
package link;
public class Link {
public int iData;
public Link next = null;
public Link(int data) {
super();
iData = data;
next = null;
}
public void displayLink(){
System.out.println("Link: {"+iData+"}");
}
public String toString(){
return "{"+iData+"}";
}
}
package link;
public class LinkList {
private Link first;
public LinkList(Link first) {
super();
this.first = first;
}
public LinkList() {
this.first = null;
}
public void insertFirst(int id){
Link link = new Link(id);
link.next = first;//the old
first = link;
}
public Link find(Link key){
Link k = first;
while(k != null){
if(k.iData == key.iData)
return k;
k = k.next;
}
return k;
}
public boolean delete(Link key){
if(key == null)
return false;
if(find(key) == null)
return false;
Link current = first;
Link pre = first;
while(current != null){
if(current.iData == key.iData){
if(current == first){//删除的是第一个元素
current = current.next;
pre = current;
first = current;
}else{
current = current.next;
pre.next = current;
}
return true;
}else{
pre = current;
current = current.next;
}
}
return false;
}
public void displayLinkList(){
System.out.println("LinkList:first --> last");
Link link = first;
while(link != null){
link.displayLink();
link = link.next;
}
}
}
package link;
public class LinkListApp {
public static void main(String args[]){
LinkList link = new LinkList();
link.insertFirst(3);
link.insertFirst(31);
link.insertFirst(2);
link.insertFirst(12);
link.insertFirst(1);
link.insertFirst(11);
link.displayLinkList();
Link f = new Link(12);
Link k = link.find(f);
if(k != null){
System.out.println("find key"+f);
k.displayLink();
}else{
System.out.println("not find key"+f);
}
boolean a = link.delete(f);
if(a){
System.out.println("delete key"+f+":"+a);
link.displayLinkList();
}else{
System.out.println("not delete key"+f+":"+a);
}
}
}