算法(Algorithms)第4版 练习 1.3.20
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了算法(Algorithms)第4版 练习 1.3.20,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2284字,纯文字阅读大概需要4分钟。
内容图文
![算法(Algorithms)第4版 练习 1.3.20](/upload/InfoBanner/zyjiaocheng/1319/0f49a19102f543e0904c87ecf5d441d2.jpg)
方法实现:
// 1.3.20 /** * delete the kth element in a linked list, if it exists. * * @param k the kth element, it should larger than 1 * @throws IllegalArgumentException if k < 1 * @throws NoSuchElementException if the size of the list is less than k */ public Item delete(int k) { if(k < 1) thrownew IllegalArgumentException("k must larger than 1"); Node<Item> precurrent = new Node<Item>(); precurrent.next = first; Item item; while(precurrent.next != null && k > 1) { precurrent = precurrent.next; k--; } if(precurrent.next == null) thrownew NoSuchElementException("LinkedList hasn‘t so many elements"); item = precurrent.next.item; if(precurrent.next == first) first = precurrent.next.next; else precurrent.next = precurrent.next.next; return item; }
测试用例:
package com.qiusongde.linkedlist; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class Exercise1320 { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); while(!StdIn.isEmpty()) { String s = StdIn.readString(); list.insertAtBeginning(s); StdOut.println("insertAtBeginning success: " + s); StdOut.println(list); } int k = 5; String s = list.delete(k); StdOut.println("delete " + k + "th Element success: "+ s); StdOut.println(list); for(int i = 0; i < 4; i++) { k = 1; s = list.delete(k); StdOut.println("delete " + k + "th Element success: "+ s); StdOut.println(list); } k = 5; s = list.delete(k); StdOut.println("delete " + k + "th Element success: "+ s); StdOut.println(list); } }
测试数据:
to
be
or
not
to
输出结果:
insertAtBeginning success: to to insertAtBeginning success: be be to insertAtBeginning success: or or be to insertAtBeginning success: not not or be to insertAtBeginning success: to to not or be to delete 5th Element success: to to not or be delete 1th Element success: to not or be delete 1th Element success: not or be delete 1th Element success: or be delete 1th Element success: be Exception in thread "main" java.util.NoSuchElementException: LinkedList hasn‘t so many elements at com.qiusongde.linkedlist.LinkedList.delete(LinkedList.java:130) at com.qiusongde.linkedlist.Exercise1320.main(Exercise1320.java:32)
原文:http://www.cnblogs.com/songdechiu/p/6512590.html
内容总结
以上是互联网集市为您收集整理的算法(Algorithms)第4版 练习 1.3.20全部内容,希望文章能够帮你解决算法(Algorithms)第4版 练习 1.3.20所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。