从反转链表学习算法题ACM写法
作者:
Roc_8
,
2025-07-06 18:38:16
· 北京
,
所有人可见
,
阅读 4
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 Main{
public static ListNode reverseList(ListNode head){
ListNode dummy = new ListNode(-1);
dummy.next = head;
if (head == null) return head;
ListNode a = dummy.next;
ListNode b = a.next;
while (b != null){
ListNode tmp = b.next;
b.next = a;
a = b;
b = tmp;
}
head.next = null;
return a;
}
public static ListNode createList(int[] nums){
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
for (int i = 0; i < nums.length; i ++){
tail = tail.next = new ListNode(nums[i]);
}
return dummy.next;
}
public static void printList(ListNode head){
ListNode p = head;
while (p != null){
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
return;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int n = sc.nextInt();
if (n == 0) {
System.out.println("list is empty");
break;
}
int[] nums = new int[n];
for (int i = 0; i < n; i ++) nums[i] = sc.nextInt();
ListNode head = createList(nums);
printList(head);
head = reverseList(head);
printList(head);
}
return;
}
}