JAVA编写一个单链表类的成员方法,实现将第i个结点的数据值修改为x。
时间: 2024-05-12 17:21:17 浏览: 24
以下是JAVA编写的单链表类的成员方法,实现将第i个结点的数据值修改为x:
```java
public class LinkedList {
private Node head; // 头结点
private int size; // 链表长度
// 节点类
private class Node {
int val; // 数据域
Node next; // 指针域
Node(int val, Node next) {
this.val = val;
this.next = next;
}
}
// 将第i个节点的数据值修改为x
public void modify(int i, int x) {
if (i < 1 || i > size) {
throw new IndexOutOfBoundsException("Index out of bounds!");
}
Node p = head;
for (int j = 1; j < i; j++) {
p = p.next;
}
p.val = x;
}
}
```
在这个单链表类中,我们提供了一个`modify`方法,该方法接收两个参数,分别是要修改结点的位置i和要修改的数据值x。在方法中,我们首先判断i是否越界,然后遍历链表找到第i个结点,并将其数据值修改为x。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)