Java单链表插入元素算法实现 - 在指定位置插入节点
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class LinkedList {
private ListNode head;
public LinkedList() {
head = null;
}
// 在第i个结点之前插入元素x
public boolean insert(int i, int x) {
if (i < 0 || i > getLength()) {
return false;
}
ListNode newNode = new ListNode(x);
if (i == 0) {
newNode.next = head;
head = newNode;
} else {
ListNode current = head;
for (int j = 0; j < i - 1; j++) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
return true;
}
// 获取链表长度
public int getLength() {
int length = 0;
ListNode current = head;
while (current != null) {
length++;
current = current.next;
}
return length;
}
// 打印链表
public void printList() {
ListNode current = head;
while (current != null) {
System.out.print(current.val + ' ' );
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(0, 6);
list.insert(1, 1);
list.insert(2, 2);
list.insert(3, 3);
list.insert(4, 4);
list.insert(5, 5);
list.printList(); // 输出:6 1 2 3 4 5
}
}
原文地址: https://www.cveoy.top/t/topic/pgVf 著作权归作者所有。请勿转载和采集!