双向链表
package linkedList;
public class DoubleLinkedListDemo {
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);
doubleLinkedList.show();
System.out.println("删除后的链表------------------");
doubleLinkedList.delete(4);
doubleLinkedList.show();
}
}
class DoubleLinkedList{
private HeroNode2 head= new HeroNode2(0, "", "");
public HeroNode2 getHead() {
return head;
}
public void add(HeroNode2 heroNode) {
HeroNode2 temp=head;
while(true) {
if(null == temp.next) {
break;
}
temp = temp.next;
}
temp.next=heroNode;
heroNode.pre=temp;
}
public void addByOrder(HeroNode2 heroNode) {
HeroNode2 temp=head;
boolean flag = false;
while(true) {
if(null == temp.next) {
break;
}
if(temp.next.no > heroNode.no) {
break;
}else if(temp.next.no == heroNode.no) {
flag=true;
break;
}
temp = temp.next;
}
if(flag) {
System.out.printf("准备插入的元素%d已经存在,不能添加\n", heroNode.no);
}else {
heroNode.next = temp.next;
temp.next = heroNode;
}
}
public void delete(int no) {
if(null == head.next) {
System.out.println("链表为空,不能进行删除操作");
return;
}
HeroNode2 temp=head.next;
boolean flag = false;
while(true) {
if(null == temp) {
break;
}
if(temp.no == no) {
flag = true;
break;
}
temp = temp.next;
}
if(flag) {
temp.pre.next=temp.next;
if(null != temp.next) {
temp.next.pre=temp.pre;
}
}else {
System.out.println("删除的节点不存在");
}
}
public void update(HeroNode2 heroNode) {
if(null == head.next) {
System.out.println("链表为空");
return;
}
HeroNode2 temp=head.next;
boolean flag = false;
while(true) {
if(null == temp) {
break;
}
if(temp.no == heroNode.no) {
flag=true;
break;
}
temp=temp.next;
}
if(flag) {
temp.name=heroNode.name;
temp.nickName=heroNode.nickName;
}else {
System.out.println("没有找到对应的节点");
}
}
public void show() {
if(null == head.next) {
System.out.println("链表为空");
return;
}
HeroNode2 temp=head.next;
while(true) {
if(null == temp) {
break;
}
System.out.println(temp);
temp=temp.next;
}
}
}
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 +"]";
}
}