Data structure - doubly linked list

Article directory

Table of contents

Article directory

Preface

1. What is a doubly linked list?

What are the advantages of doubly linked lists?

2. Design and implementation of doubly linked list

1. Design thinking

Tail append: Add a new element to the end of the linked list

 Head insertion: Insert a node at the head of the linked list

 Delete: Delete nodes based on the value of val

 Find: Find and return nodes based on the value of the index

Summarize



Preface

Hello everyone, today I will explain to you the design and implementation of a doubly linked list. The difference from the one-way linked list is that a pointer to the previous node is added to the doubly linked list.


1. What is a doubly linked list?

As shown in the figure above, the doubly linked list contains two pointers, one pointing to the predecessor node and one pointing to the successor node. The head node has no predecessor node and the tail node has no successor node.

Predecessor  : The predecessor refers to the node before the current node, that is, the node before the current node in the linked list. It can be accessed through the previous pointer.

Successor  : The successor refers to the node after the current node, that is, the node located after the current node in the linked list. It can be accessed through the next pointer.

What are the advantages of doubly linked lists?

Compared with singly linked list, doubly linked list has the following advantages:

  1. You can start from any node and traverse forward or backward. Since each node has a pointer to the previous node and the next node, forward and backward traversal operations can be easily performed in the linked list.

  2. When inserting and deleting nodes, there is no need to traverse the entire linked list to find the previous node. In a singly linked list, if you want to insert or delete a node after a certain node, you need to find the previous node of the node first, while the doubly linked list can find the previous node directly through the pointer, thus improving the efficiency of insertion and deletion operations.

  3. Doubly linked lists can make reverse search more convenient. In a singly linked list, if you want to find the previous node of a node, you need to traverse the entire linked list starting from the head node, while a doubly linked list can directly find the previous node through the backward pointer, thus realizing reverse search.

In short, doubly linked lists have higher efficiency and flexibility in traversal, insertion and deletion operations than singly linked lists. However, the disadvantage of a doubly linked list is that it requires more memory space to store additional pointers.

2. Design and implementation of doubly linked list

1. Design thinking

Preface: For simplicity, we only define the most basic properties in the class

Node class: Whether it is a doubly linked list or a one-way linked list, it is composed of nodes, so the node class is essential (it is worth mentioning that the node class does not have to be defined as an external class. If you think about it, it seems It is more appropriate to define it as an internal class. After all, the node is part of the linked list. If you implement it yourself, you can use the internal class method. Since I am preparing a blog using the external class method, I will not modify it here.)

Linked list class: What information should be included in the class? Smart readers must have thought of it, nodes! You are all smart people. In addition to nodes, we also need to include a member variable Head (the head node of the linked list), A construction method (the linked list is written for others to use), and other member methods (designed by yourself).

The framework code is given below

public class List {
    private Node head;//head node

    public List() {

    }

// node class
class Node {
    int val;
    Node prev;
    Node next;

    public Node() {
    }

    public Node(int val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + val +
                ", prev=" + prev +
                ", next=" + next +
                '}';
    }
}

2. Code implementation

Preface: For the sake of simplicity, we will only implement the basic methods below and only focus on analyzing the parts of the code that I think are difficult for beginners.

Same as the previous part of the code, some very simple methods are given directly

/*
*The number of elements in the linked list
* */
public int getSize(){
    Node cur = head;
    
    int count = 0;
    
    while(cur != null){
        cur = cur.next;
        count++;
    }
    return count;
}

/*
* Determine whether the linked list is empty
* */
public Boolean IsEmpty() {
    return head == null;
}

Tail append: Add a new element to the end of the linked list

public void addNode(int val) {
    Node node = new Node(val);
    if (IsEmpty()) {
        //The linked list is empty, this node is the new head
        head = node;
    }

    Node cur = head;

    while (cur.next != null) {
        cur = cur.next;
    }

    // Cur at this time represents the last node
    cur.next = node;
    node.prev = cur;
}

 Head insertion: Insert a node at the head of the linked list

I don’t know if beginners find it difficult. I personally feel that these codes are very basic, so I didn’t analyze them.

If you have any questions, you can ask them in the comment area and I will make corrections.

public void addFirst(int val){
    Node newNode = new Node(val);
    if(IsEmpty()){
        head = newNode;
    }
    newNode.next = head;
    head.prev = newNode;
    head = newNode;
}

 Delete: Delete nodes based on the value of val

This is much simpler than a singly linked list. In a singly linked list, you need to find the previous node with a value of val, and you also need to determine whether the head node is val. Please understand the method in a singly linked list, and this in a doubly linked list It's my brother!

//Delete nodes based on their no value
public void DeleteNode(int no) {
    int count = 0; // Record the number of deleted nodes
    
    if(IsEmpty()){
        System.out.println("The linked list is empty");
        return;
    }
    Node cur = head;//Assign the value of head to the variable cur, so that it can replace head for loop traversal
    while(true){
        if(cur == null){
            System.out.println("A total of "+count+" nodes were deleted");
            // There is no node with value no in the linked list, jump out of the loop
            break;
        }

        if(cur.val == no){
            Node prev = cur.prev;//Record the previous node of the node to be deleted
            cur = cur.next; // Overwrite the current node with the next node
            cur.prev = prev;
            count++;
            continue;
        }
        cur = cur.next;
    }

 Find: Find and return nodes based on the value of the index

//Find node based on index
public Node findNode(int index) throws IndexException {
    // Whether the index is legal or not. As soon as you see the issues related to the index, you should think about whether you need to judge the legality of the index. You need to judge here.
    if(index < 0 || index >= getSize()){
        // Customize exception to indicate illegal behavior such as index out of bounds
        throw new IndexException("Index out of bounds");
    }
    
    Node cur = head;
    while(index > 0){
        index--;
        cur = cur.next;
    }
    
    return cur;
}

 Writing this, I have to express my feelings about the affectionate brother in JAVA - Exception (Exception) - Part 1_Blog that likes eating animal milk - The next article of the CSDN blog has not been written yet

It's over here, the method is more refined than too many, let's understand it by yourself!


Summarize

In this blog, you should focus on the design of linked lists. In coding, interviews are more about singly linked lists, and most of the questions you ask are singly linked lists. Doubly linked lists are not that important.

Guess you like

Origin blog.csdn.net/weixin_73869209/article/details/132743911