import java.util.Scanner;
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
ListNode(int val, ListNode next){
this.val = val;
this.next = next;
}
}
public class link {
public static void main(String[] args) {
//int[] arr = {1,2,3,4,5};
Scanner scanner = new Scanner(System.in);
String[] split = scanner.nextLine().split(" ");
int[] arr = new int[split.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.parseInt(split[i]);
}
ListNode head = help(arr);
//翻转链表
head = reverse(head);
//打印链表
while(head != null){
System.out.print(head.val);
if(head.next != null){
System.out.print("->");
}
head = head.next;
}
}
//翻转链表
private static ListNode reverse(ListNode head) {
if(head == null){
return null;
}
ListNode cur = head;
ListNode pre = null;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
//数组封装成为链表
private static ListNode help(int[] arr) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
for (int i = 0; i < arr.length; i++) {
ListNode node = new ListNode(arr[i]);
cur.next = node;
cur = cur.next;
if(i == arr.length - 1){
cur.next = null;
}
}
return dummy.next;
}
}
acm模式Java传参链表和输入(以翻转链表为例)
于 2022-03-11 21:01:24 首次发布