先建立学生模型:
再建立链表业务模型:
public class MyLink { public Student s; public MyLink nextone; public MyLink() { } public MyLink(Student x) { s = x; nextone = null; } // add public void add(Student x) { MyLink pre=this,t = nextone; while (t != null) { pre=t; t = t.nextone; } pre.nextone = new MyLink(x); System.out.println("add success."); } // delete public void del(Student x) { MyLink pre = this, p = nextone; Student t; while (p != null) { t = p.s; if (t.name.equals(x.name) && t.age == x.age) { pre.nextone = p.nextone; // p=p.nextone;连续删除应该有这句,无下句 break; } else { pre = p; p = pre.nextone; } } } // modify--modi age by name public void modi(String x, int y) { MyLink t = nextone; while (t != null) { if (t.s.name.equals(x)) { t.s.age = y; break;// 连续修改应该没有这句 } t = t.nextone; } } // get student by xm public Student get(String x) { MyLink t = nextone; while (t != null) { if (t.s.name.equals(x)) { return t.s; } t = t.nextone; } return null; } //display all public void displayAll() { MyLink t = nextone; while (t != null) { t.s.showMe(); t = t.nextone; } } }
主程序调用:
运行结果:
先理解,然后写一下。
会写了,就用链表改写书上的例子。