一、数据结构与算法:
Step 1) 创建 HeroNode2 双向链表类:
class HeroNode2 {
public int no;
public String name;
public String nickName;
public HeroNode2 next;
public HeroNode2 pre;
public HeroNode2(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 + '\'' +
//", next=" + next +
'}';
}
}
Step 2) 创建 双链表表头:
class DoubleLinkedList {
private HeroNode2 head = new HeroNode2(0, "", "");
public HeroNode2 getHead() {
return head;
}
public void list(){
if(head.next == null){
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
while(true){
if(temp == null){
break;
}
System.out.println(temp+"\r\n");
temp = temp.next;
}
System.out.println();
}
}
Step 3) 新建 add 添加 双向链表元素的方法:
public void add(HeroNode2 heroNode){
HeroNode2 temp = head;
while(true){
if(temp.next == null){
break;
}
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
Step 4) 新建 list 遍历 双向链表元素的方法:
public void list(){
if(head.next == null){
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
while(true){
if(temp == null){
break;
}
System.out.println(temp+"\r\n");
temp = temp.next;
}
System.out.println();
}
Step 5) 新建 updata 更新 双向链表元素的方法:
public void updata(HeroNode2 newHeroNode){
if(head.next == null){
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
boolean flag = false;
while (true){
if(temp == null){
break;
}
if(temp.no == newHeroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag == true){
temp.name = newHeroNode.name;
temp.nickName = newHeroNode.nickName;
}else{
System.out.println("没有找到需要修改的编号");
}
}
Step 6) 新建 del 删除 双向链表元素的方法:
public void del(int no){
HeroNode2 temp = head;
if(head.next == null){
System.out.println("链表为空");
return;
}
boolean flag = false;
while (true){
if(temp.next == null){
break;
}
if(temp.next.no == no){
temp = temp.next;
flag = true;
break;
}
temp = temp.next;
}
if(flag == true){
temp.pre.next = temp.next;
if(temp.next != null) {
temp.next.pre = temp.pre;
}
}else{
System.out.println("没有找到需要删除的编号");
}
}
Step 7) main 方法:
public static void main(String[] args) {
HeroNode2 heroNode1 = new HeroNode2(1, "宋江", "及时雨");
HeroNode2 heroNode2 = new HeroNode2(2, "瑞军", "王启林");
HeroNode2 heroNode3 = new HeroNode2(3, "无用", "之多新");
HeroNode2 heroNode4 = new HeroNode2(4, "林冲", "豹子头");
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
doubleLinkedList.add(heroNode1);
doubleLinkedList.add(heroNode2);
doubleLinkedList.add(heroNode3);
doubleLinkedList.add(heroNode4);
System.out.println("修改前");
doubleLinkedList.list();
}
• 由 ChiKong_Tam 写于 2020 年 9 月 8 日