线性结构3 —— 双向链表

一、介绍

 双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。

二、代码

 节点
class Node {
    int no;
    String data;
    Node pre; // 前节点
    Node next; // 后节点

    public Node(int no, String data) {
        this.no = no;
        this.data = data;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                ", data='" + data + '\'' +
                '}';
    }
}
 双向链表
class DoubleLinkedList {
    private Node headNode = new Node(0, "");

    public Node headNode() {
        return headNode;
    }

    // 遍历双向链表
    public void show() {
        if (headNode.next == null) {
            return;
        }
        Node temp = headNode.next;
        while (temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }
    }

    // 添加元素
    public void add(Node node) {
        Node temp = headNode;
        while (temp != null) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = node;
        node.pre = temp;
    }

    // 修改元素
    public void update(Node node) {
        if (headNode.next == null) {
            System.out.println("链表为空");
        }
        Node temp = headNode.next;
        while (true) {
            if (temp == null) {
                break;
            }
            if (temp.no == node.no) {
                temp.data = node.data;
                return;
            }
            temp = temp.next;
        }
        System.out.println("没有找到指定元素");
    }

    // 删除节点
    public void delete(int no) {
        if (headNode.next == null) {
            return;
        }
        Node temp = headNode.next;
        boolean flag = false;
        while (true) {
            if (temp == null) {
                break;
            }
            if (temp.no == no) {
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag) {
            temp.pre.next = temp.next;
            if (temp.next != null) {
                temp.next.pre = temp.pre;
            }
        } else {
            System.out.printf("节点:%d 不存在\n", no);
        }
    }
}

三、测试

public class DoubleLinkedListDemo {
    public static void main(String[] args) {
        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
        doubleLinkedList.add(new Node(1, "test1"));
        doubleLinkedList.add(new Node(2, "test2"));
        doubleLinkedList.add(new Node(3, "test3"));
        doubleLinkedList.show();
        System.out.println("-------------------");
        doubleLinkedList.update(new Node(2, "test4"));
        doubleLinkedList.show();
        System.out.println("-------------------");
        doubleLinkedList.delete(2);
        doubleLinkedList.show();
    }
}

猜你喜欢

转载自www.cnblogs.com/gary97/p/12290395.html