class Link{
public int iData;
public double dData;
public Link next;//指向下一个数据指针
public Link(int id,double dd) {
iData=id;
dData=dd;
}
public void displayLink() {
System.out.println("{"+iData+","+dData+"}");
}
}
class LinkList{
private Link first;
public LinkList() {
first=null;
}
//在表头插入数据
public void insertFirst(int id,double dd) {
Link newLink=new Link(id,dd);
newLink.next=first;
first=newLink;
}
//查找包含指定关键字的链表结点,时间复杂度为o(n)
public Link find(int key) {
Link current=first;
while(current.iData!=key) {
if(current.iData!=key) {
if(current.next==null) {
return null;
}else {
current=current.next;
}
}
}
return current;
}
//查找包含指定关键字的链表结点,时间复杂度为o(n)public Link find(double key) {
Link current=first;
while(current.dData!=key) {
if(current.dData!=key) {
if(current.next==null) {
return null;
}else {
current=current.next;
}
}
}
return current;
}
//删除指定某个链结点,时间复杂度为o(n)
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 displayList() {
System.out.println("List(first-》last):");
Link current=first;
while(current!=null) {
current.displayLink();
current=current.next;
}
System.out.println();
}
}
public class LinkListApp {public static void main(String[] args) {
LinkList theList=new LinkList();
theList.insertFirst(22, 2.1);
theList.insertFirst(23, 2.3);
theList.insertFirst(25, 2.5);
theList.insertFirst(28, 2.8);
theList.displayList();
Link f=theList.find(22);
Link g=theList.find(2.1);
if(f!=null||g!=null) {
System.out.println("found the data:"+f.iData);
System.out.println("found the data:"+g.dData);
}else {
System.out.println("don't find link");
}
Link d=theList.delete(25);
if(d!=null) {
System.out.println("delete the date:"+d.iData);
}else {
System.out.println("can't find link");
}
theList.displayList();
}
}