双向链表的增删改查
class MM {
public static void main(String[] args) {
doublelist list = new doublelist();
Node node1 = new Node(1, "林冲");
Node node2 = new Node(2, "吴用");
Node node3 = new Node(3, "鲁智深");
Node node4 = new Node(4, "张三");
Node node5 = new Node(6, "张三");
Node nodeNew = new Node(4, "武松");
list.add(node1);
list.add(node2);
list.add(node3);
list.add(node4);
list.add(node5);
list.showAll();
list.del(2);
System.out.println("----------------");
list.showAll();
System.out.println("----------------");
list.addByNo(node2);
list.showAll();
list.del(4);
System.out.println("---------------4");
list.addByNo(node4);
list.showAll();
System.out.println("---------------改");
list.update(nodeNew);
list.showAll();
}
}
class doublelist {
Node head = new Node(0, "");
//增加 尾部
public void add(Node node) {
Node temp = head;
while (true) {
if (temp.next == null) break;
temp = temp.next;
}
temp.next = node;
node.pre = temp;
}
//按照序号添加
public void addByNo(Node node) {
Node cur = head;
while (true) {
if (cur == null) break;
if (cur.no > node.no) {
System.out.println("找到添加的位置了" + cur.no);
break;
}
cur = cur.next;
}
//与单链表不同的是 需要 双链表需要 双线连接,pre与next属性都要赋值;
cur.pre.next = node;
node.next = cur;
node.pre = cur.pre;
cur.pre = node;
// node.next=cur.next;
// node.pre=cur;
}
public void del(int n) {
Node cur = head;
boolean flag = false;
while (true) {
if (cur.next == null) break;
if (cur.no == n) {
flag = true;
break;
}
cur = cur.next;
}
if (flag) {
cur.pre.next = cur.next;
if (cur.next != null)
cur.next.pre = cur.pre;
} else {
System.out.println("没有找到该节点!" + n);
}
}
//改
public void update(Node node) {
Node temp = head.next;
boolean flag = false;
while (true) {
if (temp.next == null) break;
if (temp.no == node.no) {
flag = true;
break;
}
temp = temp.next;
}
if (flag)
temp.setName(node.getName());
else
System.out.println("不存在改节点");
}
public void showAll() {
Node cur = head.next;
while (true) {
if (cur == null) break;
System.out.println(cur);
cur = cur.next;
}
}
}
class Node {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int no;
public String name;
public Node next;
public Node pre;
public Node(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}