在第i个结点前插入值为x的结点。 实验测试数据基本要求: 第一组数据:链表长度n≥10,x=100, i分别为5,n,n+1,0,1,n+2 第二组数据:链表长度n=0,x=100,i=5
时间: 2024-03-07 15:49:04 浏览: 128
好的,你需要实现一个在单向链表中在第i个结点前插入值为x的结点的方法。代码如下:
```java
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
class Solution {
public ListNode insert(ListNode head, int x, int i) {
if (i < 1) {
ListNode node = new ListNode(x);
node.next = head;
return node;
}
ListNode prev = null;
ListNode curr = head;
while (i > 1 && curr != null) {
i--;
prev = curr;
curr = curr.next;
}
if (i > 1) {
return head;
}
ListNode node = new ListNode(x);
node.next = curr;
if (prev != null) {
prev.next = node;
} else {
head = node;
}
return head;
}
}
public class Main {
public static void main(String[] args) {
ListNode head = null;
int n = 10;
for (int i = n; i >= 1; i--) {
ListNode node = new ListNode(i);
node.next = head;
head = node;
}
Solution solution = new Solution();
head = solution.insert(head, 100, 5);
head = solution.insert(head, 100, n);
head = solution.insert(head, 100, n + 1);
head = solution.insert(head, 100, 0);
head = solution.insert(head, 100, 1);
head = solution.insert(head, 100, n + 2);
ListNode node = head;
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
System.out.println();
head = null;
head = solution.insert(head, 100, 5);
node = head;
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
System.out.println();
}
}
```
第一组数据中,我们创建一个长度为10的单向链表,然后分别在第5个、第n个、第n+1个、第0个、第1个、第n+2个结点前插入值为100的结点。第二组数据中,我们创建一个空链表,然后在第5个结点前插入值为100的结点。
阅读全文