1.单链表反转
public class Main {
public static void main(String[] args) {
HeroSingleLinkedList heroSingleLinkedList = new HeroSingleLinkedList();
System.out.println("-------------以下是添加---------------");
heroSingleLinkedList.addByOrder(new Hero(1,"宋江","及时雨"));
heroSingleLinkedList.addByOrder(new Hero(3,"吴用","智多星"));
heroSingleLinkedList.addByOrder(new Hero(2,"李逵","黑旋风"));
heroSingleLinkedList.showHeros();
reverseLinkedList(heroSingleLinkedList).showHeros();
}
//反转
public static HeroSingleLinkedList reverseLinkedList(HeroSingleLinkedList oldHeroSingleLinkedList){
Hero oldHead = oldHeroSingleLinkedList.head;
//如果链表为空或只有一个节点 则无需反转
if (oldHead.next == null || oldHead.next.next == null){
System.out.println("无需反转");
return null;
}else {
Hero cur = oldHead.next;
Hero curNext = cur.next;
HeroSingleLinkedList newHeroSingleLinkedList = new HeroSingleLinkedList();
while (cur != null){
curNext = cur.next;//当时不知道把他放到第一行 而且写成了= curNext.next
//将旧链表的每一个节点连到新链表的第一个
cur.next = newHeroSingleLinkedList.head.next;
newHeroSingleLinkedList.head.next = cur;
cur = curNext;
}
//这一步就是将旧的链表和新的链表弄成一样的 统一起来
//其实我感觉有没有都可以,只是取决于是否要更改旧链表
oldHeroSingleLinkedList.head.next = newHeroSingleLinkedList.head.next;
return newHeroSingleLinkedList;
}
}
}
class HeroSingleLinkedList{
//有头节点
Hero head = new Hero(0,"","");
//按顺序添加
public void addByOrder(Hero hero){
Hero temp = head;
boolean flag = false;//标志是否已存在该节点
while (true){
//如果链表为空,则直接添加
if (temp.next == null){
break;
}else if (temp.next.num > hero.num){
break;
}else if (temp.next.num == hero.num){
flag = true;
}
//别忘了后移
temp = temp.next;
}
if (flag){
System.out.println("已存在相同序号节点,故无法添加");
return;
}else {
hero.next = temp.next;
temp.next = hero;
}
}
//显示链表
public void showHeros(){
if (head.next == null){
System.out.println("该链表为空");
return;
}
Hero temp = head;
while (true){
temp = temp.next;
System.out.println(temp);
if (temp.next == null){
break;
}
}
}
}
class Hero{
int num;
String name;
String nickName;
Hero next;
Hero(int num,String name,String nickName){
this.num = num;
this.name = name;
this.nickName = nickName;
next = null;
}
@Override
public String toString() {
return "Hero{" +
"num=" + num +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}
尤其要注意框出来的这两句的顺序,如果弄得不对,极容易出现空指针异常
2.单链表逆序打印
方式一,可以先反转再打印
方式二,可以利用栈,先将单链表每个元素都依次入栈,然后依次出栈即可
public static void printLinkedListReversal(HeroSingleLinkedList heroSingleLinkedList){
if (heroSingleLinkedList.head.next == null){
System.out.println("为空,不能打印");
return;
}
//创建一个栈
Stack<Hero> stack = new Stack<>();
//遍历单链表,依次入栈
Hero cur = heroSingleLinkedList.head.next;
while (cur != null){
stack.push(cur);
cur = cur.next;
}
//依次出栈,打印
while (stack.size() > 0){
Hero pop = stack.pop();
System.out.println(pop);
}
}
结果与上面的一样