- /**
- *
- * @author Markus Roggenbach, and commenting by Marcus Chung(2012487), Steven Abbott-Williams 2010050
- * - no copyright
- * @version 11.0.8
- * last edited - 15/02/2021
- * This shows an example of how a stack using a linked list works.
- */
- import java.util.NoSuchElementException;
- public class StackLinkedList<T> {
- private Link head;
- private Link tail;
- public StackLinkedList() {
- head = null;
- tail = null;
- }
- public boolean isEmpty(){
- return((this.head == null) && (this.tail == null));
- }
- /**
- * adds new element to top of stack
- * @param element to be added to top of stack
- */
- public void push(T element){
- Link newNode = new Link (element, head);
- this.head = newNode;
- }
- /**
- *
- * @return returns the value to be removed from top of stack
- */
- public T pop() {
- if (this.isEmpty()){
- throw new NoSuchElementException();
- }
- this.head = this.head.getNext();
- return (T) this.head;
- }
- /**
- * checks whats on top of stack
- * @return top elem of stack
- */
- public T peek(){
- if (this.isEmpty()){
- throw new NoSuchElementException();
- }
- return (T) this.head.getElement();
- }
- /**
- * removes all elements in stack
- * kinda
- */
- public void removeAll(){
- if (this.isEmpty()){
- throw new NullPointerException();
- }
- this.head = null;
- this.tail = null;
- }
- /**
- * checks if stack contains e
- * @param e value to compare to the top element of the stack to see if the same.
- * @return Returns true if this StackLinkedList contains the specified el-ement else return false.
- */
- public boolean contains(T e){
- boolean found = false;
- if (this.isEmpty()){
- throw new NullPointerException();
- }
- while(!this.isEmpty() && !found) {
- //this.head = this.head.getNext(); wrong
- if (this.head.getElement() == e) {
- found = true;
- return true;
- }
- }
- return (this.head.getElement() == e);
- }
- }
[text] linkedlistStackMC
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Editor
You can edit this paste and save as new: