您的位置:首页 > 其它

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

2017-10-22 15:50 274 查看

问题

给出一段代码,删除链表的尾结点,其中链表的首结点为first。

解决思路

为删除尾结点,需要找到倒数第二个结点。尾结点为node->next == null。将倒数第二个结点置为null,即可。

/*
...| current | -> | next | -> | null |

*/


同时对first为空和只有一个结点的情况进行特殊处理。

代码

/**
* Description :
* Author      : mn@furzoom.com
* Date        : Oct 24, 2016 4:13:20 PM
* Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved.
*/
package com.furzoom.lab.algs.ch103;

/**
* ClassName    : E10319 <br>
* Function     : TODO ADD FUNCTION. <br>
* date         : Oct 24, 2016 4:13:20 PM <br>
*
* @version
*/
public class E10319
{
private class Node
{
int item;
Node next;
}

private Node first;

public void deleteLastNode()
{
Node current = first;
if (current == null) return;

Node next = current.next;
if (next == null) first = null;

while (next.next != null)
{
current = next;
next = next.next;
}
current.next = null;
}
}


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

算法-第四版习题索引汇总
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: