算法-第四版-练习1.3.26解答
来源:互联网 发布:core keygen mac 下载 编辑:程序博客网 时间:2024/05/16 04:51
问题
编写一个方法insertAfter(),接受一个链表和一个字符串key作为参数,删除链表中所有item域为key的结点。
解决思路
遍历链表,删除元素结点,注意别断链。复杂度O(N)。
由于使用类来封装,这里只需提供一个字符串参数即可。
代码
public void remove(Item item) { while (first != null && item.equals(first.item)) { first = first.next; } Node<Item> current = first; Node<Item> node; while (current != null && current.next != null) { node = current.next; if (item.equals(node.item)) { current.next = node.next; } else { current = node; } } }
测试代码:
/** * Description : * Author : mn@furzoom.com * Date : Oct 25, 2016 10:28:24 AM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */package com.furzoom.lab.algs.ch103;/** * ClassName : E10326 <br> * Function : TODO ADD FUNCTION. <br> * date : Oct 25, 2016 10:28:24 AM <br> * * @version */public class E10326{ public static void main(String[] args) { LinkList<String> ll = new LinkList<String>(); ll.append("a"); ll.append("a"); ll.append("a"); ll.printList(); ll.remove("b"); System.out.println("After remove(\"b\"): "); ll.printList(); ll.remove("a"); System.out.println("After remove(\"a\"): "); ll.printList(); ll.append("b"); ll.append("b"); ll.append("a"); ll.append("a"); ll.append("b"); ll.append("b"); ll.append("b"); System.out.println("new list: "); ll.printList(); ll.remove("b"); System.out.println("After remove(\"b\"): "); ll.printList(); ll.append("b"); ll.append("b"); ll.append("a"); ll.append("a"); ll.append("b"); ll.append("b"); ll.append("b"); System.out.println("another new list: "); ll.printList(); ll.remove("a"); System.out.println("After remove(\"a\"): "); ll.printList(); }}
结果:
aaaAfter remove("b"): aaaAfter remove("a"): new list: bbaabbbAfter remove("b"): aaanother new list: aabbaabbbAfter remove("a"): bbbbb
算法-第四版-1.3 背包、队列和栈-习题索引汇总
算法-第四版习题索引汇总
0 0
- 算法-第四版-练习1.3.26解答
- 算法-第四版-练习1.3.1解答
- 算法-第四版-练习1.3.2解答
- 算法-第四版-练习1.3.3解答
- 算法-第四版-练习1.3.4解答
- 算法-第四版-练习1.3.5解答
- 算法-第四版-练习1.3.6解答
- 算法-第四版-练习1.3.7解答
- 算法-第四版-练习1.3.8解答
- 算法-第四版-练习1.3.9解答
- 算法-第四版-练习1.3.10解答
- 算法-第四版-练习1.3.11解答
- 算法-第四版-练习1.3.12解答
- 算法-第四版-练习1.3.13解答
- 算法-第四版-练习1.3.14解答
- 算法-第四版-练习1.3.15解答
- 算法-第四版-练习1.3.16解答
- 算法-第四版-练习1.3.17解答
- Android Studio开发入门-引用jar及so文件
- 内联元素(inline)和块级元素(block)
- 文章标题
- objective-c 中数据类型之一 几何数据类型(CGPoint,CGSize,CGRect)
- Material Design 学习笔记(1)
- 算法-第四版-练习1.3.26解答
- linux下关于进程优先级
- SunnyAmy 面向对象设计七大原则
- 蓝牙系统结构
- Kylin元数据备份日志
- TCP流模式 与 UDP报文模式
- CString成员函数用法
- Java – Convert date and time between timezone
- React-native 之WebView的使用