栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

复制代码 代码如下:

public class NodeList {
 private static class Node { // 节点类
  E data; // 节点上的数据
  Node next; // 指向下一个节点

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

 private Node head; // 链表的头节点
 private Node last; // 链表的尾节点
 private Node other = null;
 private int length = 0; // 节点数量

 
 public NodeList() {
  // 默认节点为空
  this.head = new Node(null);
 }

 
 public NodeList(E data) {
  this.head = new Node(data);
  this.last = head;
  length++;
 }

 
 public void add(E data) {
  if (isEmpty()) {
   head = new Node(data);
   last = head;
   length++;
  } else {
   Node newNode = new Node(data);
   last.next = newNode;
   last = newNode;
  }
 }

 
 public E get(int index){
  if(index<0 || index>length){
   throw new IndexOutOfBoundsException("索引越界:"+index);
  }
  other = head;
  for(int i=0;i   other = other.next;
  }
  return other.data;
 }

 
 public boolean set(E oldValue,E newValue){
  other = head;
  while(other!=null){
   if(other.data.equals(oldValue)){
    other.data = newValue;
    return true;
   }
   other = other.next;
  }
  return false;
 }

 
 public boolean add(E data, E insertData) {
  other = head;
  while (other != null) {
   if (other.data.equals(data)) {
    Node newNode = new Node(insertData);
    Node temp = other.next;
    newNode.next = temp;
    other.next = newNode;
    length++;
    return true;
   }
   other = other.next;
  }
  return false;
 }

 
 public boolean contains(E data){
  other = head;
  while(other!=null){
   if(other.data.equals(data)){
    return true;
   }
   other = other.next;
  }
  return false;
 }

 
 public boolean remove(E data){
  other = head;
  Node temp = head;  //临时变量,用于保存前一个节点
  while(other!=null){
   if(other.data.equals(data)){
    temp.next = other.next;
    length--;
    return true;
   }
   temp = other;
   other = other.next;
  }
  return false;
 }

 
 public boolean isEmpty() {
  return length == 0;
 }

 
 public void clear() {
  this.head = null;
  this.length = 0;
 }

 
 public void printlink() {
  if(isEmpty()){
   System.out.println("空链表");
  }else{
   other = head;
   while (other != null) {
    System.out.print(other.data);
    other = other.next;
   }
   System.out.println();
  }
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152334.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号