方法实现:
//1.3.19 /** * remove the last node in the linked list whose first node is first * * @return return the item of the last node * @throws NoSuchElementException if this Linked List is empty */ public Item removeTheLast() { Node<Item> precurrent; Item item = null; precurrent = findPreLastNode(); //has not found if(precurrent.next == null) { throw new NoSuchElementException("LinkedList is empty"); } item = precurrent.next.item; //some implementation will add one empty node as head, and head.next = first //if so, it's not necessary to have if condition here if(precurrent.next == first) first = first.next; else precurrent.next = precurrent.next.next; return item; } /** * return the previous last node * * @return return the previous last node. * If the last node is the first node, the previous last node is a virtual one */ private Node<Item> findPreLastNode() { Node<Item> precurrent = new Node<Item>(); precurrent.next = first; //find the previous last node //precurrent.next is the same as current while(precurrent.next != null && precurrent.next.next != null) { precurrent = precurrent.next; } return precurrent; }
测试用例:
package com.qiusongde.linkedlist; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class Exercise1319 { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); while(!StdIn.isEmpty()) { String s = StdIn.readString(); list.insertAtBeginning(s); StdOut.println("insertAtBeginning success: " + s); StdOut.println(list); } String s = list.removeTheLast(); StdOut.println("removeTheLast success: " + s); StdOut.println(list); } }
测试数据1:
to
be
or
not
to
be
输出结果:
insertAtBeginning success: to
to
insertAtBeginning success: be
be to
insertAtBeginning success: or
or be to
insertAtBeginning success: not
not or be to
insertAtBeginning success: to
to not or be to
insertAtBeginning success: be
be to not or be to
removeTheLast success: to
be to not or be
测试数据2:
to
输出结果:
insertAtBeginning success: to
to
removeTheLast success: to
测试数据3:
输入为空
输出结果:
Exception in thread "main" java.util.NoSuchElementException: LinkedList is empty at com.qiusongde.linkedlist.LinkedList.removeTheLast(LinkedList.java:73) at com.qiusongde.linkedlist.Exercise1319.main(Exercise1319.java:18)