单链表:无序添加、有序添加、遍历、反转
package com.example.notes.linkedlist;
import lombok.Data;
import static com.example.notes.linkedlist.SingleLinkedList.reversetList;
/**
* 单向链表
* 17
*
* @date 2022/3/16 - 15:03
*/
public class SingleLinkedListDemo {
public static void main(String[] args) {
HeroNode heroNode1 = new HeroNode(1, "宋江", "及时雨");
HeroNode heroNode2 = new HeroNode(2, "卢俊义", "玉麒麟");
HeroNode heroNode3 = new HeroNode(3, "吴勇", "智多星");
HeroNode heroNode4 = new HeroNode(4, "林冲", "豹子头");
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.addByOrder(heroNode4);
singleLinkedList.addByOrder(heroNode1);
singleLinkedList.addByOrder(heroNode3);
singleLinkedList.addByOrder(heroNode2);
singleLinkedList.list();
System.out.println("-------------------------------------------------");
reversetList(singleLinkedList.getHead());
singleLinkedList.list();
System.out.println("-------------------------------------------------");
}
}
//定义
@Data
class SingleLinkedList {
//初始化头结点
private HeroNode head = new HeroNode(0, "", "");
/*
* 不考虑编号顺序
* */
public void add(HeroNode heroNode) {
//因为head节点不能动,需要一个辅助遍历temp
HeroNode temp = head;
while (true) {
//找到链表最后
if (temp.next == null) {
break;
}
//如果不是最后则后移
temp = temp.next;
}
temp.next = heroNode;
}
/*
* 考虑编号顺序
* */
public void addByOrder(HeroNode heroNode) {
//因为head节点不能动,需要一个辅助遍历temp
HeroNode temp = head;
boolean exist = false;
while (true) {
//找到链表最后
if (temp.next == null) { //当前为temp链表最后
break;
}
if (temp.next.no > heroNode.no) { //找到位置
break;
} else if (temp.next.no == heroNode.no) {
exist = true;
break;
}
//如果不是正确位置则后移
temp = temp.next;
}
if (exist) {
System.out.println("数据已存在!");
} else {
heroNode.next = temp.next;
temp.next = heroNode;
}
}
public void list() {
if (head.next == null) {
System.out.println("链表为空!");
}
HeroNode temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
/*
* 链表反转
* 22
* */
public static void reversetList(HeroNode heroNode) {
//空链表或只有一个数据的链表,无需反转直接返回
if (heroNode.next == null && heroNode.next.next == null) {
return;
}
//定义辅助变量
HeroNode cur = heroNode.next; //当前节点,遍历原先链表
HeroNode next = null; //当前节点的下一个节点
HeroNode reversetHead = new HeroNode(0, "", "");
while (cur != null) {
next = cur.next;
cur.next = reversetHead.next;
reversetHead.next = cur;
cur = next;
}
heroNode.next = reversetHead.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 +
'}';
}
}