java实现线性表中的链式存储

来源:互联网 发布:aim聊天软件 编辑:程序博客网 时间:2024/06/05 08:09
链式存储与顺序存储相比较,更节省空间,更加方便的删除和插入
/**  * @author NEOSONG* @date Oct 7, 2017 * 10:18:26 AM* program OF information:   1.定义节点类   */class Node {private Node next;//指针域 private T data;//数据域    //构造方法//无参构造public Node(){next=null;}public Node(Node next){//仅有指针域,无数据域this.next=next;}public Node(T data){//仅有数据域,无指针域this.data=data;next=null;}public Node(T data,Node next){//都有this.data=data;this.next=next;}public Node getNext() {return next;}public void setNext(Node next) {this.next = next;}public T getData() {return data;}public void setData(T data) {this.data = data;}}/**  * @author NEOSONG* @date Oct 7, 2017 * 11:44:15 AM* program OF information:     2.定义链式表类 */public class LinkList {//定义构造方法,以初始化变量public LinkList(){header=new Node();}//定义一个头结点private Node header;//set/get方法public Node getHeader() {return header;}public void setHeader(Node header) {this.header = header;}//求长度public int count(){int i=0;//用于累加Node p=header;while(p.getNext()!=null){//循环遍历链式表中的元素p=p.getNext();i++;}return i;}//清空操作    public void clear(){    header.setNext(null);    }        //判断单链表是否为空    public boolean isEmpty(){    return header.getNext()==null;    }        //附加操作    public void attend(T data){    Node p=new Node(data);//需要附加的节点    Node r=header;//用r遍历    while(r.getNext()!=null)    r=r.getNext();    r.setNext(p);    }        //插入操作,i为位置    public void insert(T data,int i){    //为增强程序的健壮性,增加判断    //判断位置是否正确    if(i<1||i>count())    throw new RuntimeException("插入位置不正确"+i);    Node p=new Node(data);    Node r=header;    Node q=new Node();    for(int j=0;jcount())    throw new RuntimeException("删除位置不正确"+i);    Node r=header;    Node q=new Node();    for(int j=0;jcount())    throw new RuntimeException("取值位置不正确"+i);    Node r=header;    int n=1;    while(n<=i){    r=r.getNext();    n++;    }    return r.getData();    }        //定位,按值查找    public int locate(T data){    //增加判断    if(isEmpty()){    throw new RuntimeException("链式表为空,无法查询");    }    Node r=header;    int i;    for(i=1;i<=count();i++){    r=r.getNext();    if(r.getData()==data)    break;    else if(i==count()&&r.getData()!=data)    throw new RuntimeException("抱歉,没有查询到这个值!");    }    return i;    }        //输出链式表    public void printLinkList(){    if(isEmpty()){    throw new RuntimeException("链式表为空");    }    Node r=header;    while(r.getNext()!=null){    r=r.getNext();    System.out.print(r.getData()+"  ");    }    }}
原创粉丝点击