算法-第四版-练习1.3.24解答
问题
编写一个方法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);
}
}
输出:
a B c D e remove after "f": a B c D e remove after "e": a B c D e remove after "D": a B c D remove after "a": a
作者:马 岩(Furzoom) (http://www.cnblogs.com/furzoom/)
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。

浙公网安备 33010602011771号