用Java编写一段程序要求使用链表将两个数组链接在一起。第一个数组时【287】第二个数组是【92227】。新生成的链表要求打印在D盘A文件夹的abctxt文档中。abctxt文档需要提前新规
以下是使用Java编写的程序,将两个数组链接在一起,然后将生成的链表打印到D盘A文件夹的abc.txt文档中:
import java.io.FileWriter;
import java.io.IOException;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedListMerge {
public static void main(String[] args) {
int[] arr1 = {2, 8, 7};
int[] arr2 = {9, 22, 27};
Node head = null;
Node tail = null;
// 创建第一个链表
for (int i = 0; i < arr1.length; i++) {
Node newNode = new Node(arr1[i]);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
// 创建第二个链表
for (int i = 0; i < arr2.length; i++) {
Node newNode = new Node(arr2[i]);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
// 打印链表到文件
printLinkedListToFile(head, "D:\\A\\abc.txt");
}
public static void printLinkedListToFile(Node head, String filePath) {
try {
FileWriter writer = new FileWriter(filePath);
Node current = head;
while (current != null) {
writer.write(current.data + " ");
current = current.next;
}
writer.close();
System.out.println("链表已成功打印到文件 " + filePath);
} catch (IOException e) {
System.out.println("写入文件时发生错误:" + e.getMessage());
}
}
}
在运行程序之前,请确保已经在D盘A文件夹下创建了abc.txt文档。运行程序后,链表将被打印到abc.txt文档中
原文地址: http://www.cveoy.top/t/topic/hyGo 著作权归作者所有。请勿转载和采集!