一个简单的单链表,它支持:
1.在链表头插入一个数据项
2.在链表头删除一个数据项
3.遍历链表显示它的内容
public class Link{
public int iData;
public double dData;
public Link next;
public Link(int id,double dd){
iData = id;
dData = dd;
}
public void display(){
System.out.print("{"+iData+","+dData+"}");
}
}
public class LinkList{
private Link first;
public void LinkList(){
first = null;
}
public boolean isEmpty(){
return (first == null);
}
}
LinkList的构造函数把first赋值成null,这不是必须的,引用类型在创建之初会自动赋值成null。first =null代表链表没有数据项。
insertFirst() ,在链表的表头插入一个新的节点
public void insertFirst(int id,double dd){
Link newLink = new Link(id,dd);
newLink.next = first;
first = newLink;
}
deleteFirst(),删除表头节点
public Link deleteFirst(){
List temp = first;
first = first.next;
return temp;
}
displayList()显示链表的所有内容
public void displayList(){
System.out.println("List (first-->last): ");
List current = first;
while(current != null){
current.dispalyLink();
current = current.next;
}
System.out.println(" ");
}
查找和删除指定节点
public Link find (int key){
Link current = first ;
while(current.iData !=key){
if(current.next == null){
return null;
}else{
current = current.next;
}
}
return current;
}
public Link delete(int key){
Link current = first;
Link previous = first;
while(current.iData != key){
if(current.next ==null){
return null;
}else{
previous = current;
current = current.next;
}
}
if(current ==first){
first = first.next;
}else{
previous.next = current.next;
return current;
}
}
在指定的链结点之后插入新节点
public void insertAfter(int key,int id,double dd ){
Link newLink = new Link(id,dd);
Link findcurrent = find(key);
if(findcurrent!=null){
newLink.next = findcurrent.next;
findcurrent.next = newLink;
}
}