栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java打印有序链表的公共部分(StreanTokenizer的简单用法)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java打印有序链表的公共部分(StreanTokenizer的简单用法)

但是最后面打印了空白符,不清楚为什么也通过测试!

package class04P;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

public class Code03P_StreamTokennier {

    public static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static int nextInt(){
        try{
            st.nextToken();
            return (int)st.nval;
        }catch(Exception e){
            e.printStackTrace();
        }

        return 0;
    }

    public static class Node{
        int val;
        Node next;

        public Node(int val){
            this.val = val;
        }
    }

    public static Node newlinkedList(int len){
        if(len == 0) return null;
        Node head = new Node(nextInt());

        Node cur = head;
        for (int i = 0; i < len - 1; i++) {
            cur.next = new Node(nextInt());
            cur = cur.next;
        }

        return head;
    }

    public static void printCommonPart(Node head1, Node head2){
        while(head1 != null && head2 != null){
            if(head1.val == head2.val){
                System.out.print(head1.val + " ");
                head1 = head1.next;
                head2 = head2.next;
            }
            else if(head1.val < head2.val){
                head1 = head1.next;
            } else if (head1.val > head2.val) {
                head2 = head2.next;
            }
        }
    }
    public static void main(String[] args) {
        Node head1 = newlinkedList(nextInt());
        Node head2 = newlinkedList(nextInt());

        printCommonPart(head1,head2);

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337096.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号