链接点以及链表实现

来源:互联网 发布:雅思词汇推荐知乎 编辑:程序博客网 时间:2024/06/04 17:40

链接点

  • 链接点中包含一个数据域和一个指针域,其中数据域用来包装数据,而指针域用来指向下一个链接点
public class Link{    //数据域    private int data;    //指针域    private Link next;    public Link(int data){        this.data=data;    }    public int getData() {        return data;    }    public void setData(int data) {        this.data = data;    }    public Link getNext() {        return next;    }    public void setNext(Link next) {        this.next = next;    }}

实现链表

  • 在插入节点到制定位置的部分,为什么只循环到pos-1
    这里写图片描述
    假如在下标2的位置插入数据,我们只需要找到1的下标在其后面插入数据即可。
public class LinkList{    //开始节点    private Link first;    //添加    public void insert(int value){        Link lnk = new Link(value);        if(first == null){            first = lnk;        }else{            lnk.setNext(first);            first = lnk;        }    }    //显示全部    public void display(){        Link current = first;        while(current != null){            System.out.println(current.getData());            current = current.getNext();        }    }    //查找节点    public Link find(int key){        Link current = first;        while(current.getData() != key){            if(current.getNext() == null){                return null;            }            current = current.getNext();        }    }    //插入节点到指定位置    public void insert(int value,int pos){        if(pos == 0){            insert(value);        }else{            Link current = first;            for(int i=0;i<pos-1;i++){                current = current.getNext();            }            Link lnk = new Link(value);            lnk.setNext(current.getNext());            current.setNext(lnk);        }    }    //删除指定节点    public void delete(int key){        Link current = first;        Link ago = first;        while(current.getData() != key){            if(current.getNext() == null){                return;            }else{                ago = current;                current = current.getNext();            }        }        if(current == first){            first = first.getNext();        }else{            ago.setNext(current.getNext());        }    }}
1 0
原创粉丝点击