1 回答

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超6個(gè)贊
此代碼:
public static <E> Node<E> insertNodeAtPosition(Node<E> head, E element, int position) {
return insertNodeAtPosition(null, head, element, position);
}
private static <E> Node<E> insertNodeAtPosition(Node<E> prev, Node<E> head, E element, int position) {
if (position == 0) {
Node<E> newNode = new Node<>(element, null);
if (prev != null) {
prev.next = newNode;
}
newNode.next = head;
return newNode;
}
return insertNodeAtPosition(head, head.next, element, position - 1);
}
將返回新插入的節(jié)點(diǎn)。
編輯:沒(méi)有額外的方法:
private static <E> Node<E> insertNodeAtPosition(Node<E> prev, Node<E> head, E element, int position) {
if (position == 0) {
Node<E> newNode = new Node<>(element, null);
if (prev != null) {
prev.next = newNode;
}
newNode.next = head;
return newNode;
}
return insertNodeAtPosition(head, head.next, element, position - 1);
}
添加回答
舉報(bào)