- package com.tw.dst.link;
- /**
- * <p>链表类</p>
- * @author tangw
- *
- */
- public class Link {
- public int iData;
- public double dData;
- public Link next;
- public Link(int idata,double ddata){
- this.iData = idata;
- this.dData = ddata;
- }
- public void displayLink(){
- System.out.println(" idata="+iData+" ddata:"+dData);
- }
- }
- package com.tw.dst.link;
- /**
- * <p>单链表</p>
- * @author tangw 2010-11-29
- *
- */
- public class LinkList {
- private Link first;//第一个链结点的引用
- public LinkList() {
- first = null;//引用类型初始化会自动赋值为null,此处不是必须的
- }
- //判断是否为空
- public boolean isEmpty(){
- return (first == null);
- }
- //插入数据
- public void insertFirst(int id,double dd){
- Link link = new Link(id,dd);
- link.next = first;
- first = link;
- }
- //删除数据
- public Link deleteFirst(){
- Link temp = first;
- first = first.next;
- return temp;
- }
- //查找指定节点
- 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 displayList(){
- System.out.println("list (first-->last)");
- Link current = first;
- while(current!=null){
- current.displayLink();
- current =current.next;
- }
- System.out.println("");
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- //----1---插入
- LinkList linkList = new LinkList();
- linkList.insertFirst(22, 2.99);
- linkList.insertFirst(44, 4.99);
- linkList.insertFirst(66, 6.99);
- linkList.displayList();
- //---2--删除
- /*while(!linkList.isEmpty()){
- Link aLink = linkList.deleteFirst();
- System.out.println("--deleted");
- aLink.displayLink();
- }
- linkList.displayList();*/
- //==3 查找=====
- Link link = linkList.find(44);
- if(null !=link){
- System.out.println("---idata:"+link.dData);
- }else{
- System.out.println("-find---no ");
- }
- //---4: 删除指定元素
- Link delLink = linkList.delete(44);
- if( null != delLink){
- System.out.println("----del link:"+delLink.dData);
- }else{
- System.out.println("-delete---no ");
- }
- linkList.displayList();
- }
- }