|
发表于 2022-4-26 10:17:54
|
显示全部楼层
本楼为最佳答案

参考参考吧,HeadInsertTest.java 文件:
- import java.util.Scanner;
- /**
- * 链表节点类
- */
- class LNode {
- public int val;
- public LNode next;
- public LNode(int val){
- this.val = val;
- }
- }
- /**
- * 测试类,以及头插法创建链表、打印输出链表方法的实现
- */
- public class HeadInsertTest {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- int count = scan.nextInt();
- scan.nextLine();
- String[][] sVal = new String[count][];
- for (int i = 0; i < count; i++){
- sVal[i] = scan.nextLine().split(" ");
- }
- for (int i = 0; i < count; i++){
- LNode head = headInsertCreateLinkedList(sVal[i]);
- printLinkedList(head);
- System.out.println();
- }
- }
- /**
- * 该方法接收一个整数字符串值数组,用头插法创建链表
- * @param sNode
- * @return
- */
- public static LNode headInsertCreateLinkedList(String[] sNode){
- if (sNode == null || sNode.length <= 1){
- return null;
- }
- LNode dummy = new LNode(-1);
- LNode node = new LNode(Integer.parseInt(sNode[0]));
- dummy.next = node;
- for (int i = 1; i < sNode.length; i++){
- if ("-1".equals(sNode[i])){
- return dummy.next;
- }
- node = new LNode(Integer.parseInt(sNode[i]));
- node.next = dummy.next;
- dummy.next = node;
- }
- return dummy.next;
- }
- /**
- * 该方法接收一个链表头节点,进行链表打印输出
- * @param head
- */
- public static void printLinkedList(LNode head){
- while (head != null){
- System.out.print(head.val + " ");
- head = head.next;
- }
- }
- }
复制代码 |
|