用java实现一个单链表,满足如下操作: 把数组A[8]={1,2,3,4,5,100,200,300}保存至单链表 在单链表第6个位置插入数值586,并显示单链表此时新的情况,比如节点数 然后对当前单链表第5个节点进行删除操作,并显示删除后单链表的状态 显示所有操作的头结点地址。
时间: 2024-02-13 10:03:24 浏览: 95
好的,以下是用Java实现单链表,并满足上述操作的代码:
```java
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedList {
ListNode head;
public LinkedList() {
this.head = null;
}
// 将数组转换成单链表
public void arrayToList(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
ListNode cur = null;
for (int i = 0; i < arr.length; i++) {
if (head == null) {
head = new ListNode(arr[i]);
cur = head;
} else {
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
}
}
// 在第k个位置插入节点
public void insertAt(int k, int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
return;
}
if (k == 1) {
newNode.next = head;
head = newNode;
return;
}
ListNode cur = head;
for (int i = 1; i < k - 1 && cur != null; i++) {
cur = cur.next;
}
if (cur == null) {
return;
}
newNode.next = cur.next;
cur.next = newNode;
}
// 删除第k个节点
public void deleteAt(int k) {
if (head == null) {
return;
}
if (k == 1) {
head = head.next;
return;
}
ListNode cur = head;
for (int i = 1; i < k - 1 && cur != null; i++) {
cur = cur.next;
}
if (cur == null || cur.next == null) {
return;
}
cur.next = cur.next.next;
}
// 打印链表
public void printList() {
ListNode cur = head;
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
System.out.println();
}
// 打印头结点地址
public void printHead() {
System.out.println("Head node address: " + head);
}
}
```
使用上述代码可以完成题目中的操作,以下是测试代码:
```java
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 100, 200, 300};
LinkedList list = new LinkedList();
list.arrayToList(arr);
System.out.print("Original list: ");
list.printList();
System.out.println("Head node address: " + list.head);
list.insertAt(6, 586);
System.out.print("After inserting 586 at position 6: ");
list.printList();
System.out.println("Head node address: " + list.head);
list.deleteAt(5);
System.out.print("After deleting the node at position 5: ");
list.printList();
System.out.println("Head node address: " + list.head);
}
```
输出结果如下:
```
Original list: 1 2 3 4 5 100 200 300
Head node address: LinkedList$ListNode@6e0be858
After inserting 586 at position 6: 1 2 3 4 5 586 100 200 300
Head node address: LinkedList$ListNode@6e0be858
After deleting the node at position 5: 1 2 3 4 586 100 200 300
Head node address: LinkedList$ListNode@6e0be858
```
阅读全文