博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法(Algorithms)第4版 练习 1.3.20
阅读量:6951 次
发布时间:2019-06-27

本文共 2701 字,大约阅读时间需要 9 分钟。

方法实现:

//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)            throw new IllegalArgumentException("k must larger than 1");                Node
precurrent = new Node
(); precurrent.next = first; Item item; while(precurrent.next != null && k > 1) { precurrent = precurrent.next; k--; } if(precurrent.next == null) throw new 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
list = new LinkedList
(); 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); }}

 

 

测试数据:

tobeornotto

 

 

输出结果:

insertAtBeginning success: toto insertAtBeginning success: bebe to insertAtBeginning success: oror be to insertAtBeginning success: notnot or be to insertAtBeginning success: toto not or be to delete 5th Element success: toto not or be delete 1th Element success: tonot or be delete 1th Element success: notor be delete 1th Element success: orbe delete 1th Element success: beException 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)

 

转载于:https://www.cnblogs.com/songdechiu/p/6512590.html

你可能感兴趣的文章
清闲逛论坛,发个我们团队常用的开发资源整理,跟兄弟们共享
查看>>
lex&yacc 9
查看>>
Anaconda 安装 OpenCV 遇到的问题
查看>>
set 集合容器实现元素的插入与中序排序
查看>>
最常使用Eclipse快捷键
查看>>
jmeter的如何设置headers
查看>>
ssh免密登入
查看>>
拖拽文件作为文件输入
查看>>
Eclipse设置智能提示
查看>>
SAP 生产订单变更管理 OCM Order Changement Management
查看>>
虚拟化这八年-【软件和信息服务】2014.11
查看>>
使用swfupload上传超过30M文件,使用FLASH上传组件
查看>>
OkHttp简介
查看>>
如何使用通用Mapper
查看>>
MYSQL建表语法(主键,外键,联合主键)
查看>>
linux基础-第十单元 系统的初始化和服务
查看>>
多线程的通信和同步(Java并发编程的艺术--笔记)
查看>>
Python格式化输出
查看>>
Linux使用du和df查看磁盘和文件夹占用空间
查看>>
java 消息机制 ActiveMQ入门实例
查看>>