链表

       链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针实现的。链表由一系列结点组成,结点可以在运行时动态生成,而且由于没有闲置的内存,因此空间效率比数组高。其插入操作可达到O(1)复杂度,但是查找或者访问特定的结点复杂度是O(n)。
一、链表优点:
  • 空间没有限制
  • 插入删除元素很快
二、链表缺点:存取速度很慢
三、链表又分了好几类:
      1、单向链表:一个节点指向下一个节点
       2、双向链表:一个节点有两个指针域
       3、循环链表能通过任何一个节点找到其他所有的节点,将两种(双向/单向)链表的最后一个结点指向第一个结点从而实现循环
四、Java实现链表
算法:
  • 遍历
  • 查找
  • 清空
  • 销毁
  • 求长度
  • 排序
  • 删除节点
  • 插入节点
1、首先定义节点类:
    public class LinearNode {
    private LinearNode next; //用于指向下一个节点
    private Object element;
 
    //创建一个空节点
    public LinearNode() {
        next = null;
        element = null;
    }
 
    //创建一个给定元素的节点
    public LinearNode(Object element) {
        next = null;
        this.element = element;
    }
 
    public LinearNode getNext() {
        return next;
    }
 
    public void setNext(LinearNode next) {
        this.next = next;
    }
 
    public Object getElement() {
        return element;
    }
 
    public void setElement(Object element) {
        this.element = element;
    }
 
    @Override
    public String toString() {
        return "{" +
                "'" + element +
                "'}";
    }
}
2、定义链表类实现增、删
   public class LinkedBag {
    private  int count; //记录当前节点在链表中的编号
    private LinearNode contents; //链表中的元素
 
    public LinkedBag() {
        count = 0;
        contents = null;
    }
 
    public int getCount() {
        return count;
    }
 
    public LinearNode getContents() {
        return contents;
    }
 
    //给链表中添加节点
    public void add(Object element){
 
        LinearNode node = new LinearNode(element);
        node.setNext(contents);
        contents = node;
        count++;
    }
    //删除链表中的给定的节点
    public Object remove(Object target){
        boolean found = false;
        LinearNode previous,current;
        Object result = null;
 
      if(contents.getElement().equals(target)){
          result = contents.getElement();
          contents = contents.getNext();
      }else{
          previous = contents;
          current = contents.getNext();
          for(int look=1;look<count&&!found;look++) {
              if (current.getElement().equals(target)) {
                  found = true;
              } else {
                  previous = current;
                  current = current.getNext();
              }
              if (!found) {
                  throw new NoSuchElementException();
              }
              result = current.getElement();
              previous.setNext(current.getNext());
          }
      }
      count--;
      return result;
    }
 
   //遍历节点
    public void  next(LinkedBag bag)
    {
        LinearNode current = bag.getContents();
        while(current != null){
            System.out.print("--->"+current.getElement());
            current = current.getNext();
        }
    }
}
 
posted @ 2019-06-13 15:42  #独狼  阅读(145)  评论(0编辑  收藏  举报