package linkedlist; public class DoublelinkedListDemo { public static void main(String[] args) { DoublelinkedList linkedList = new DoublelinkedList(); Node node1 = new Node(1, "宋江", "及时雨"); Node node2 = new Node(2, "卢俊义", "玉麒麟"); Node node3 = new Node(3, "吴用", "智多星"); Node node4 = new Node(4, "林冲", "豹子头"); linkedList.add(node1); linkedList.add(node2); linkedList.add(node3); linkedList.add(node4); System.out.println("修改前的链表:"); linkedList.list(); linkedList.update(new Node(1, "boss", "及时雨")); System.out.println("修改后的链表:"); linkedList.list(); linkedList.delete(4); System.out.println("删除后的链表:"); linkedList.list(); } static class DoublelinkedList { private final Node headNode = new Node(0, "", ""); public void add(Node node) { Node temp = headNode; while (temp.next != null) { temp = temp.next; } temp.next = node; node.pre = temp; } public void update(Node node) { Node temp = headNode.next; boolean isExit = false; while (true) { //遍历到最后一个节点了 if (temp == null) { break; } //如果找到该节点 if (temp.number == node.number) { isExit = true; break; } temp = temp.next; } if (isExit) { temp.name = node.name; temp.nickName = node.nickName; } else { System.out.printf("没有找到编号为 %d 的节点 n", node.number); } } public void delete(int index) { Node temp = headNode.next; boolean isExit = false; while (true) { //遍历到最后一个节点了 if (temp == null) { break; } //如果找到该节点 if (temp.number == index) { isExit = true; break; } temp = temp.next; } if (isExit) { temp.pre.next = temp.next; //注意删除的节点是最后一个节点时 if (temp.next != null) { temp.next.pre = temp.pre; } } else { System.out.println("没有找到节点"); } } public void list() { if (headNode.next == null) { System.out.println("空链表"); return; } Node temp = headNode.next; while (temp != null) { System.out.println(temp); temp = temp.next; } } } static class Node { public int number; public String name; public String nickName; public Node next; public Node pre; public Node(int number, String name, String nickName) { this.number = number; this.name = name; this.nickName = nickName; } @Override public String toString() { return "Node{" + "number=" + number + ", name='" + name + ''' + ", nickName='" + nickName + ''' + '}'; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)