zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java实现数据结构单链表示例(java单链表)

JAVA数据结构 实现 表示 单链
2023-06-13 09:15:19 时间

复制代码代码如下:


/**
 *单向链表
 *
 */
publicclassNodeList<E>{
 privatestaticclassNode<E>{//节点类
  Edata;//节点上的数据
  Node<E>next;//指向下一个节点

  Node(Ee){
   this.data=e;
   this.next=null;
  }
 }

 privateNode<E>head;//链表的头节点
 privateNode<E>last;//链表的尾节点
 privateNode<E>other=null;
 privateintlength=0;//节点数量

 /**
 *无参构造方法
 */
 publicNodeList(){
  //默认节点为空
  this.head=newNode<E>(null);
 }

 /**
 *初始化时创建一个节点
 *
 *@paramdata
 *           数据
 */
 publicNodeList(Edata){
  this.head=newNode<E>(data);
  this.last=head;
  length++;
 }

 /**
 *添加一个节点(尾插法)
 *
 *@paramdata
 *           数据
 */
 publicvoidadd(Edata){
  if(isEmpty()){
   head=newNode<E>(data);
   last=head;
   length++;
  }else{
   Node<E>newNode=newNode<E>(data);
   last.next=newNode;
   last=newNode;
  }
 }

 /**
 *获得索引处的数据(索引输入错误抛出越界异常)
 *@paramindex索引
 *@return索引处数据
 */
 publicEget(intindex){
  if(index<0||index>length){
   thrownewIndexOutOfBoundsException("索引越界:"+index);
  }
  other=head;
  for(inti=0;i<index;i++){
   other=other.next;
  }
  returnother.data;
 }

 /**
 *新值替换旧值
 *@return成功为true,未找到为false
 */
 publicbooleanset(EoldValue,EnewValue){
  other=head;
  while(other!=null){
   if(other.data.equals(oldValue)){
    other.data=newValue;
    returntrue;
   }
   other=other.next;
  }
  returnfalse;
 }

 /**
 *在指定元素后插入一个元素
 *
 *@paramdata
 *           指定的元素
 *@paraminsertData
 *           需要插入的元素
 *@returnfalse为未找到元素,true为插入成功
 */
 publicbooleanadd(Edata,EinsertData){
  other=head;
  while(other!=null){
   if(other.data.equals(data)){
    Node<E>newNode=newNode<E>(insertData);
    Node<E>temp=other.next;
    newNode.next=temp;
    other.next=newNode;
    length++;
    returntrue;
   }
   other=other.next;
  }
  returnfalse;
 }

 /**
 *链表中是否包含此元素
 *@return包含为true,不包含为false
 */
 publicbooleancontains(Edata){
  other=head;
  while(other!=null){
   if(other.data.equals(data)){
    returntrue;
   }
   other=other.next;
  }
  returnfalse;
 }

 /**
 *移除指定的元素
 *@paramdata需要移除的元素
 *@return不存在为false,成功为true
 */
 publicbooleanremove(Edata){
  other=head;
  Node<E>temp=head;  //临时变量,用于保存前一个节点
  while(other!=null){
   if(other.data.equals(data)){
    temp.next=other.next;
    length--;
    returntrue;
   }
   temp=other;
   other=other.next;
  }
  returnfalse;
 }

 /**
 *判断链表是否为空
 *
 *@return空为true,非空为false
 */
 publicbooleanisEmpty(){
  returnlength==0;
 }

 /**
 *清空链表
 */
 publicvoidclear(){
  this.head=null;
  this.length=0;
 }

 /**
 *输出所有节点
 */
 publicvoidprintLink(){
  if(isEmpty()){
   System.out.println("空链表");
  }else{
   other=head;
   while(other!=null){
    System.out.print(other.data);
    other=other.next;
   }
   System.out.println();
  }
 }
}