java实现单链表
简单插入与展示
package com.algorithm.demo4;
public class LinkedListDemo {
public static void main(String[] args) {
Node user01 = new Node(1, "user01");
Node user02 = new Node(2, "user02");
Node user03 = new Node(3, "user03");
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.add(user01);
singleLinkedList.add(user02);
singleLinkedList.add(user03);
singleLinkedList.show();
}
}
class SingleLinkedList {
private Node head = new Node(0, "head");
public void add(Node node) {
Node tem = head;
// 遍历链表
while (true) {
// 走到最后
if (tem.getNext() == null) {
break;
}
// tem后移
tem = tem.getNext();
}
// 出循环后tem就指向最后的节点
tem.setNext(node);
}
public void show() {
if (isEmpty()) {
System.out.println("空的");
return;
}
Node tem = head.getNext();
while (true) {
// 如果到最后了
if (tem == null) {
break;
}
// 输出
System.out.println(tem);
// tem后移
tem = tem.getNext();
}
}
public boolean isEmpty() {
return head.getNext() == null;
}
}
class Node {
private int id;
private String name;
private Node next;
@Override
public String toString() {
return "Node{" +
"id=" + id +
", name='" + name + '\'' +
", next=" + next +
'}';
}
public Node(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
按id顺序插入
public void addByOrder(Node node) {
Node tem = head;
int id = node.getId();
if (id == tem.getId()) {
System.out.println("编号已存在");
return;
}
// 遍历链表
while (true) {
// 如果走到最后
if (tem.getNext() == null) {
break;
}
// 如果tem后一个的id大于node的id,说明node任然在tem左边
// 如果tem的id小于node的id,说明node在tem右边
// 都符合时说明在两节点之间
if ((tem.getNext().getId() > node.getId()) && (tem.getId() < node.getId())) {
break;
}
// tem右移
tem = tem.getNext();
}
// 插入
if (tem.getNext() != null) {
node.setNext(tem.getNext());
}
tem.setNext(node);
}
修改和删除
public void delete(Node node) {
if (head.getNext() == null) {
System.out.println("链表空的");
return;
}
Node tem = head;
boolean flag = false;
int id = node.getId();
while (true) {
if (tem.getNext() == null) {
break;
}
if (tem.getNext().getId() == id){
flag = true;
break;
}
// tem 右移
tem = tem.getNext();
}
// 根据flag判断
if (flag) {
// 删除
tem.setNext(tem.getNext().getNext());
node.setNext(null);
}else {
System.out.println("找不到");
}
}
public void update(Node node) {
if (head.getNext() == null) {
System.out.println("链表空的");
return;
}
Node tem = head.getNext();
boolean flag = false;
int id = node.getId();
while (true) {
if (tem == null) {
break;
}
if (id == tem.getId()) {
flag = true;
break;
}
// tem右移
tem = tem.getNext();
}
// 根据flag判断
if (flag) {
// 修改
tem.setId(node.getId());
tem.setName(node.getName());
}else {
System.out.println("找不到");
}
}