📅  最后修改于: 2023-12-03 15:26:03.921000             🧑  作者: Mango
题目要求实现一个双向链表的插入方法,要求在指定位置插入节点,如果位置大于链表长度,则将节点插入到链表末尾。
首先,需要定义一个双向链表的节点类,包含前指针、后指针和节点值:
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++;
}
}