📌  相关文章
📜  教资会网络 | UGC NET CS 2016 年 8 月 – II |问题 3(1)

📅  最后修改于: 2023-12-03 15:26:03.921000             🧑  作者: Mango

UGC NET CS 2016 August - II Question 3

题目要求实现一个双向链表的插入方法,要求在指定位置插入节点,如果位置大于链表长度,则将节点插入到链表末尾。

解题思路

首先,需要定义一个双向链表的节点类,包含前指针、后指针和节点值:

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

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

接着,需要定义一个双向链表类,包含头节点和长度:

class DoublyLinkedList {
    Node head;
    int length;

    public DoublyLinkedList() {
        this.head = null;
        this.length = 0;
    }
}

插入方法需要判断插入位置是否大于链表长度,如果是则将节点插入到链表末尾,否则按照指定位置插入:

public void insertAtPosition(int val, int pos) {
    Node newNode = new Node(val);

    if (pos > length) {
        pos = length;
    }

    if (pos == 0) {
        newNode.next = head;
        head.prev = newNode;
        head = newNode;
    } else {
        Node curr = head;
        for (int i = 0; i < pos - 1; i++) {
            curr = curr.next;
        }
        newNode.prev = curr;
        newNode.next = curr.next;
        if (curr.next != null) {
            curr.next.prev = newNode;
        }
        curr.next = newNode;
    }

    length++;
}
完整代码
class Node {
    Node prev;
    Node next;
    int val;

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

class DoublyLinkedList {
    Node head;
    int length;

    public DoublyLinkedList() {
        this.head = null;
        this.length = 0;
    }

    public void insertAtPosition(int val, int pos) {
        Node newNode = new Node(val);

        if (pos > length) {
            pos = length;
        }

        if (pos == 0) {
            newNode.next = head;
            head.prev = newNode;
            head = newNode;
        } else {
            Node curr = head;
            for (int i = 0; i < pos - 1; i++) {
                curr = curr.next;
            }
            newNode.prev = curr;
            newNode.next = curr.next;
            if (curr.next != null) {
                curr.next.prev = newNode;
            }
            curr.next = newNode;
        }

        length++;
    }
}