算法-第四版-练习1.3.24解答

来源:互联网 发布:mysql5.7数据库下载 编辑:程序博客网 时间:2024/06/03 21:07

问题

编写一个方法removeAfter(),接受一个链表结点作为参数并删除该结点的后续结点(如果参数结点或参数结点的后续结点为空则什么也不做)。

解决思路

迭代删除其后续结点。

代码

    public void removeAfter(Node<Item> node)    {        if (node == null || node.next == null)            return;        Node<Item> current = node.next;        Node<Item> next = current.next;        node.next = null;        while (current.next != null)        {            current = null;            current = next;            next = next.next;        }    }        public Node<Item> search(Item item)    {        Node<Item> current = first;        while (current != null)        {            if (item.equals(current.item))            {                return current;            }            current = current.next;        }        return null;    }

测试代码:

/** * Description :  * Author      : mn@furzoom.com * Date        : Oct 24, 2016 6:06:52 PM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */package com.furzoom.lab.algs.ch103;/** * ClassName    : E10324 <br> * Function     : TODO ADD FUNCTION. <br> * date         : Oct 24, 2016 6:06:52 PM <br> *  * @version  */public class E10324{    public static void main(String[] args)    {        LinkList<String> ll = new LinkList<String>();        ll.append("a");        ll.append("B");        ll.append("c");        ll.append("D");        ll.append("e");                LinkList.printList(ll);                Node<String> node = ll.search("f");        ll.removeAfter(node);        System.out.println("remove after \"f\": ");        LinkList.printList(ll);                node = ll.search("e");        ll.removeAfter(node);        System.out.println("remove after \"e\": ");        LinkList.printList(ll);                node = ll.search("D");        ll.removeAfter(node);        System.out.println("remove after \"D\": ");        LinkList.printList(ll);                node = ll.search("a");        ll.removeAfter(node);        System.out.println("remove after \"a\": ");        LinkList.printList(ll);    }           }

输出:

aBcDeremove after "f": aBcDeremove after "e": aBcDeremove after "D": aBcDremove after "a": a


算法-第四版-1.3 背包、队列和栈-习题索引汇总

算法-第四版习题索引汇总


0 0
原创粉丝点击