双向链表的增删改实现
问题:运行update02 方法时 为什么说找不到更新的结点呢
```java
package Linkedlist;
public class DoubleLinkedListDemo {
//test area:
public static void main(String[] args) {
System.out.println("DLL test:");
//create nodes
HeroNode02OfDLL no1 = new HeroNode02OfDLL(1, "q", "q");
HeroNode02OfDLL no2 = new HeroNode02OfDLL(2, "xx", "aaq");
HeroNode02OfDLL no3 = new HeroNode02OfDLL(3, "zzq", "qzz");
//create DLL
DoubleLinkedList DLLForTest = new DoubleLinkedList();
DLLForTest.add02(no1);
DLLForTest.add02(no2);
DLLForTest.add02(no3);
DLLForTest.list02();
//update method
HeroNode02OfDLL newHeroNode = new HeroNode02OfDLL(2, "xxx", "xxx");
DLLForTest.update02(newHeroNode);
System.out.println("update version:");
DLLForTest.list02();
//delete method
DLLForTest.delete02(3);
System.out.println("deleted version:");
DLLForTest.list02();
}
}
class DoubleLinkedList {//create a DLL
private HeroNode02OfDLL head = new HeroNode02OfDLL(0, "", "");
public HeroNode02OfDLL getHead() {
return head;
}
//1.go through method
public void list02() {
if (head.next == null) {
System.out.println("the DLL is empty!");
return;
}
HeroNode02OfDLL temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public void add02(HeroNode02OfDLL heroNode) { //2.add at the last
HeroNode02OfDLL temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
//3.update
public void update02(HeroNode02OfDLL newHeroNode) {
if (head.next == null) {
System.out.println("the DLL is empty!");
return;
}
HeroNode02OfDLL temp = head.next;
boolean flag = false;//flag: weather find the node
while (true) {
if (temp == null) {//finished
break;
}
temp = temp.next;
}
if (flag) {
temp.name = newHeroNode.name;
temp.nickname = newHeroNode.nickname;
} else {
System.out.println("can't find the node :" + newHeroNode + "and can't update");
}
}
public void delete02(int no) {//4.delete method
if (head.next == null) {
System.out.println("DLL is empty!");
return;
}
HeroNode02OfDLL temp = head;
boolean flag = false;
while (true) {
if (temp.next == null) {//走到最后的最后
break;
}
if (temp.no == no) ;//找到待删除节点,双向链表可以自我删除
flag = true;
temp = temp.next;
}
if (flag) {
temp.pre.next = temp.next;
if (temp.next != null) {
temp.next.pre = temp.pre;//如果是最后一个节点就不用执行这一句,否则出现空指针
}
} else {
System.out.printf("the node %d should be delete doesn't exist\n", no);
}
}
}
class HeroNode02OfDLL {
public int no;
public String name;
public String nickname;
public HeroNode02OfDLL next;//default is null
public HeroNode02OfDLL pre;//default is null
public HeroNode02OfDLL(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 + "]";
}
}
```