user618712
user618712

Reputation: 1523

Delete last value of a list and returns the deleted value?

How can I write a method that deletes the last value of a list and returns the deleted value? If the list is empty, it should throw an exception. This is for a linkedlist class.

Thanks!

edit: nevermind! i'm allowed to use the java built in method. thanks!

Upvotes: 0

Views: 212

Answers (5)

Andreas Dolk
Andreas Dolk

Reputation: 114767

I hear a distant pop coming from a Stack ;)

Unfortunatly, Stack is a subclass of Vector and not of LinkedList (Hint hidden behind the last link ;) )

Upvotes: 1

John Giotta
John Giotta

Reputation: 16934

LinkedList has a method called remove

http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html#remove%28int%29

It will return the element removed.

Upvotes: 0

alpian
alpian

Reputation: 4748

Is this homework? LinkedList in Java has a removeLast method with returns the element removed.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the removeLast() method from LinkedList. If your variable is of type List then this method will not be available, you may have to cast it back to LinkedList again/change the type to LinkedList

Upvotes: 1

NVade
NVade

Reputation: 278

java.util.LinkedList has the removeLast() method out of the box...

Upvotes: 4

Related Questions