Java实现单链表的增删改以及排序
使用Java代码模拟单链表的增删改以及排序功能
代码如下:
package com.seizedays.linked_list; public class SingleLinkedListDemo {
// 主方法 public static void main(String[] args) { HeroNode node1 = new HeroNode(1, "宋江", "及时雨"); HeroNode node2 = new HeroNode(2, "卢俊义", "玉麒麟"); HeroNode node3 = new HeroNode(3, "吴用", "智多星"); HeroNode node4 = new HeroNode(4, "林冲", "豹子头"); HeroNode node5 = new HeroNode(3, "李逵", "黑旋风"); SingleLinkedList list = new SingleLinkedList(); // list.add(node1); // list.add(node2); // list.add(node3); list.addByOrder(node1); list.addByOrder(node3); // list.addByOrder(node5); list.update(node5); list.addByOrder(node2); list.addByOrder(node4); list.delete(5); list.showList(); } } //定义SingleLinkedList管理结点 class SingleLinkedList { //先初始化一个头节点,头节点不动 不存放数据 private HeroNode head = new HeroNode(0, "", ""); //1.添加节点到单向列表 // 不考虑编号顺序时候 将最后节点的next指向新的节点 public void add(HeroNode heroNode) { //temp用于辅助遍历 HeroNode temp = head; //找到最后 while (temp.next != null) { //找到链表的最后 跳出 temp = temp.next; } //当退出while循环时候 temp指向链表的最后 temp.next = heroNode; } // 2.按照编号大小有规律地将节点插入链表 public void addByOrder(HeroNode heroNode) { //通过辅助节点遍历来找到添加的位置 HeroNode temp = head; while (temp.next != null) { if (heroNode.no == temp.next.no){ System.out.printf("编号%d已经存在,不能加入\n", heroNode.no); return; } if (heroNode.no < temp.next.no) { heroNode.next = temp.next; temp.next = heroNode; return; } temp = temp.next; } temp.next = heroNode; } //3.根据编号来修改节点的信息 //根据newNode的no来修改节点 public void update(HeroNode newNode){ if (head.next == null){ System.out.println("链表为空"); return; } HeroNode temp = head; while (temp.next != null){ if (temp.next.no == newNode.no){ newNode.next = temp.next.next; temp.next = newNode; break; } temp = temp.next; } } //4.删除节点 public void delete(int no){ if (head.next == null){ System.out.println("链表为空 删除失败"); return; } HeroNode temp = head; while (temp.next != null){ if (temp.next.no == no){ temp.next = temp.next.next; System.out.println("删除完成"); return; } temp = temp.next; } System.out.println("没有找到对应节点,删除失败"); } // 显示链表 public void showList() { if (head.next == null) { System.out.println("链表为空"); return; } //head不能动 用辅助变量来遍历 HeroNode temp = head.next; while (temp != null) { //输出节点信息 System.out.println(temp); //节点后移 temp = temp.next; } } } //定义头结点 class HeroNode { public int no; public String name; public String nickname; public HeroNode next; //指向下一个结点 public HeroNode(int no, String name, String nickname) { this.no = no; this.name = name; this.nickname = nickname; } @Override public String toString() { return "HeroNode{" + "no=" + no + ", name='" + name + '\'' + ", nickname='" + nickname + '\'' + '}'; } }