1.概述
Java代码实现单链表
链表只能单向遍历,不能插入null值,包括基本的增删改查功能
2.代码
链表节点类,用来保存对象,已经一个指向下一个节点的引用类型
package org.poiuy.structure.common;
public class PoiNode<E> {
/**
* 用来存储数据
*/ private E item;
/**
* 访问下一个节点
*/ public PoiNode next;
public PoiNode(E item,PoiNode next){
this.item = item;
this.next = next;
}
public E getItem(){
return item;
}
} |
链表实现
package org.poiuy.structure.table.singlelist;
import org.poiuy.exception.common.PoiException;
import org.poiuy.structure.common.PoiNode;
/**
* 简单链表
*/public class PoiList<E> {
private PoiNode<E> node;
/**
* 链表的长度
*/ private int size;
/**
* 添加方法,添加节点到链表
* @param e
* @return
*/ public E add(E e){
if(e == null){
throw new PoiException("节点不能为空");
}
if(node == null){
node = new PoiNode<>(e,null);
size++;
return e;
}
PoiNode tmp = node;
while(tmp.next != null){
tmp = tmp.next;
}
tmp.next = new PoiNode<>(e,null);
size++;
return e;
}
/**
* 插入到指定位置
* @param index
* @param e
* @return
*/ public E add(int index,E e){
throw new PoiException("接口未开发");
}
/**
* 获取链表指定位置的节点
* @param index
* @return
*/ public E get(int index){
if(index > size){
throw new PoiException("超出链表最大边界");
}
PoiNode tmp = node;
for(int i = 0;i < index ;i++){
tmp = tmp.next;
}
return (E) tmp.getItem();
}
/**
* 删除节点
* @param e
* @return
*/ public E delete(E e){
PoiNode preNode = node;
PoiNode tmp = node;
while(tmp.next != null && !tmp.getItem().equals(e)){
preNode = tmp;
tmp = tmp.next;
}
if(tmp == null){
return null;
}
if(tmp == node){
node = node.next;
}
preNode.next = tmp.next;
E result = (E) tmp.getItem();
tmp = null;
size--;
return result;
}
/**
* 根据index删除节点
* @param index
* @return
*/ public E delete(int index){
throw new PoiException("接口未开发");
}
/**
* 获取链表的长度
* @return
*/ public int size(){
return size;
}
/**
* 判断链表是否为空
* @return
*/ public boolean empty(){
return size == 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
PoiNode<E> tmp = node;
while (tmp != null){
sb.append(tmp.getItem()).append(",");
tmp = tmp.next;
}
sb = sb.delete(sb.length() - 1,sb.length());
sb.append("]");
return sb.toString();
}
} |
测试
package org.poiuy.structure.table.singlelist;
public class PoiListApplication {
public static void main(String[] args) {
PoiList<String> list = new PoiList<>();
for(int i = 0;i < 10;i++){
list.add(String.valueOf(i));
}
System.out.println(list);
System.out.println(list.get(9));
System.out.println(list.delete("0"));
System.out.println(list);
}
} |
输出结果,可以看到增删查没有什么问题
文章来源:智云一二三科技
文章标题:单链表实现(Java版本)
文章地址:https://www.zhihuclub.com/180975.shtml