AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

从反转链表学习算法题ACM写法

作者: 作者的头像   Roc_8 ,  2025-07-06 18:38:16 · 北京 ,  所有人可见 ,  阅读 4


0


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;
    }
}


0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息