[text] linkedlistStackMC

Viewer

copydownloadembedprintName: linkedlistStackMC
  1. /**
  2.  *
  3.  *  @author Markus Roggenbach, and commenting by Marcus Chung(2012487), Steven Abbott-Williams 2010050
  4.  *  - no copyright
  5.  *  @version 11.0.8
  6.  *  last edited - 15/02/2021
  7.  *  This shows an example of how a stack using a linked list works.
  8.  */
  9.  
  10. import java.util.NoSuchElementException;
  11.  
  12.  
  13. public class StackLinkedList<T> {
  14. private Link head;
  15. private Link tail;
  16.  
  17.     public StackLinkedList() {
  18.     head = null;
  19.     tail = null;
  20. }
  21.  
  22.     public boolean isEmpty(){
  23.     return((this.head == null) && (this.tail == null));
  24. }
  25.  
  26.     /**
  27.      * adds new element to top of stack
  28.      * @param element to be added to top of stack
  29.      */
  30.     public void push(T element){
  31.     Link newNode = new Link (element, head);
  32.     this.head = newNode;
  33. }
  34.  
  35.     /**
  36.      *
  37.      * @return returns the value to be removed from top of stack
  38.      */
  39.     public T pop() {
  40.     if (this.isEmpty()){
  41.         throw new NoSuchElementException();
  42.     }
  43.     this.head = this.head.getNext();
  44.     return (T) this.head;
  45. }
  46.  
  47.     /**
  48.      * checks whats on top of stack
  49.      * @return top elem of stack
  50.      */
  51.     public T peek(){
  52.     if (this.isEmpty()){
  53.         throw new NoSuchElementException();
  54.     }
  55.     return (T) this.head.getElement();
  56. }
  57.  
  58.     /**
  59.      * removes all elements in stack
  60.      * kinda
  61.      */
  62.     public void removeAll(){
  63.     if (this.isEmpty()){
  64.         throw new NullPointerException();
  65.     }
  66.     this.head = null;
  67.     this.tail = null;
  68. }
  69.  
  70.     /**
  71.      * checks if stack contains e
  72.      * @param e value to compare to the top element of the stack to see if the same.
  73.      * @return Returns true if this StackLinkedList contains the specified el-ement  else  return  false.
  74.      */
  75.     public boolean contains(T e){
  76.         boolean found = false;
  77.     if (this.isEmpty()){
  78.         throw new NullPointerException();
  79.     }
  80.     while(!this.isEmpty() && !found) {
  81.         //this.head = this.head.getNext(); wrong
  82.         if (this.head.getElement() == e) {
  83.             found = true;
  84.             return true;
  85.         }
  86.     }
  87.     return (this.head.getElement() == e);
  88. }
  89.  
  90. }
  91.  

Editor

You can edit this paste and save as new:


File Description
  • linkedlistStackMC
  • Paste Code
  • 28 Feb-2021
  • 2.09 Kb
You can Share it: