0
点赞
收藏
分享

微信扫一扫

链表题目ACM格式

import java.util.Scanner;
/*
* 链表的输入输出(以反转链表为例)
* */
public class Main01 {
    //创建ListNode
    static 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 static ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        ListNode pre = null;
        while(head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
    public static void main(String[] args) {
        //按照1,2,3,4,5的输入来构建链表
        Scanner sc = new Scanner(System.in);
        String[] s = sc.nextLine().split(",");
        ListNode head = new ListNode(Integer.parseInt(s[0]));
        ListNode cur = head;
        for(int i = 1; i < s.length; i++) {
            cur.next = new ListNode(Integer.parseInt(s[i]));
            cur = cur.next;
        }
        //得到反转之后的结果5,4,3,2,1
        ListNode root = reverseList(head);
        //打印结果54321
        while(root != null) {
            System.out.print(root.val);
            root = root.next;
        }
    }
举报

相关推荐

0 条评论