链表实现列表
链表概念
1)链表是有序的列表
2)链表是以节点的方式存储数据,是链式存储
3)每个节点都包括data数据以及next节点
4)链表分为带头结点的链表和不带头结点的链表,根据实际需求定
代码实现
定义一个具体存储数据node,用于存储数据以及指向下个node节点地址
/**
* 定义一个存储数据的node
* */
public class Node {
public Node(int id ,String name, int sort) {
this.id = id;
this.name = name;
this.sort = sort;
}
//名称
private String name;
//排序
private int sort;
private int id;
//下一个节点
private Node nextNode;
@Override
public String toString() {
return "Node{" +
"name='" + name + '\'' +
", sort=" + sort +
", id=" + id +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
自定义一个链表实现最基础的功能新增/修改/删除/遍历等
//单向列表
public class SingletonLinkedList {
Node head = null;
//初始化一个Node作为头节点
SingletonLinkedList(){
head = new Node(0,"",0);
}
/**
* 添加node节点(根据sort字段从小到大排序)
* */
public void addSortNode(Node n){
Node temp = head;
Boolean b = false;
//找到插入位置
while(true){
//如果是空说名是空列表直接在后面增加即可
if(temp.getNextNode()==null){
break;
}
//循环多次找到当前temp的下一个节点node sort大于需要插入的node sort,说明是该team位置插入
if(temp.getNextNode().getSort()>n.getSort()){
break;
}
//相等的话修改boolean值用于抛出异常
if(temp.getNextNode().getSort()==n.getSort()){
b=true;
}
temp =temp.getNextNode();
}
if(b){
throw new RuntimeException("排序重复");
}else{
Node node = temp.getNextNode();
n.setNextNode(node);
temp.setNextNode(n);
}
}
/**
*添加一个node直接到尾节点
*/
public void addNode(Node n){
//获取到尾节点,nextNode为空则为尾节点
Node temp = head;
while(true){
if(temp.getNextNode()==null){
break;
}
temp = temp.getNextNode();
}
temp.setNextNode(n);
}
/**
* 根据id删除一个节点
*/
public void deleteNode(int id){
Node temp = head;
Boolean b = false;
while(true){
if(temp.getNextNode().getId()==id){
b = true;
break;
}
temp = temp.getNextNode();
}
if(!b){
throw new RuntimeException("id不存在");
}
temp.setNextNode(temp.getNextNode().getNextNode());
}
/**
* 遍历
* */
public void ergodic(){
Node temp = head;
while(true){
if(temp.getNextNode()==null){
break;
}
temp = temp.getNextNode();
System.out.println(temp);
}
}
/**
* 修改节点(传递node根据id进行修改name)
* */
public void updateNode(int id,String name){
Node temp = head;
Boolean b = false;
while(true){
if(temp.getId()==id){
b=true;
break;
}
temp = temp.getNextNode();
}
if(!b){
throw new RuntimeException("id不存在!");
}
temp.setName(name);
}
}
测试
public static void main(String[] args) {
SingletonLinkedList singletonLinkedList = new SingletonLinkedList();
singletonLinkedList.addSortNode(new Node(1,"张三",5));
singletonLinkedList.addSortNode(new Node(2,"李四",15));
singletonLinkedList.addSortNode(new Node(3,"王五",10));
singletonLinkedList.addSortNode(new Node(4,"猴六",7));
singletonLinkedList.deleteNode(3);
singletonLinkedList.updateNode(4,"张六六");
singletonLinkedList.ergodic();
}