问题
给出一段代码,删除链表的尾结点,其中链表的首结点为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;
}
}