算法-第四版-练习1.3.15解答
问题
编写一个Queue的用例,接受一个命令行参数k并打印出标准输入中的倒数第k个字符串(假设标准输入中至少有k个字符串)。
解决思路
将所有参数入列,得到参数数量n,出列前n-k个参数,得到倒数第k个参数。
代码
Queue:
/** * Description : * Author : mn@furzoom.com * Date : Sep 28, 2016 10:21:54 AM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch103; import java.util.Iterator; import edu.princeton.cs.algs4.StdIn; /** * ClassName : Queue <br> * Function : TODO ADD FUNCTION. <br> * date : Sep 28, 2016 10:21:54 AM <br> * * @version */ public class Queue<Item> implements Iterable<Item> { private Node first; private Node last; private int n; private class Node { Item item; Node next; } public boolean isEmpty() { return first == null; } public int size() { return n; } public void enqueue(Item item) { Node oldlast = last; last = new Node(); last.item = item; last.next = null; if (isEmpty()) { first = last; } else { oldlast.next = last; } n++; } public Item dequeue() { Item item = first.item; first = first.next; if (isEmpty()) { last = null; } n--; return item; } @Override public Iterator<Item> iterator() { return new QueueIterator(); } private class QueueIterator implements Iterator<Item> { private Node current = first; @Override public boolean hasNext() { return current != null; } @Override public Item next() { Item item = current.item; current = current.next; return item; } } public static void main(String[] args) { Queue<String> q = new Queue<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) { q.enqueue(item); } else if (!q.isEmpty()) { System.out.print(q.dequeue() + " "); } } System.out.println("(" + q.size() + " left on queue)"); } }
测试:
/** * Description : * Author : mn@furzoom.com * Date : Oct 20, 2016 4:15:54 PM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch103; import java.util.Scanner; /** * ClassName : E10315 <br> * Function : TODO ADD FUNCTION. <br> * date : Oct 20, 2016 4:15:54 PM <br> * * @version */ public class E10315 { public static void main(String[] args) { int k = Integer.parseInt(args[0]); Scanner scanner = new Scanner(System.in); Queue<String> q = new Queue<String>(); while (scanner.hasNext()) { q.enqueue(scanner.next()); } scanner.close(); int size = q.size(); for (int i = 0; i < size - k; i++) { // System.out.print(q.dequeue() + " "); q.dequeue(); } System.out.println(q.dequeue()); } }
结果:
>java -cp ".;../lib/algs4.jar" com .furzoom.lab.algs.ch103.E10315 2 1 2 3 4 5 4
作者:马 岩(Furzoom) (http://www.cnblogs.com/furzoom/)
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。