Skip to content

Instantly share code, notes, and snippets.

@katychuang
Last active January 10, 2020 18:58
Show Gist options
  • Save katychuang/637a8f9694edb2f65658a9d09b08b82c to your computer and use it in GitHub Desktop.
Save katychuang/637a8f9694edb2f65658a9d09b08b82c to your computer and use it in GitHub Desktop.
CISC 3130 Spring 2020 OER Code Snippets for https://libguides.brooklyn.cuny.edu/cisc3130/
/* Simple Linked List with Insert First */
class SimpleLinkedList {
private Node first; // private link to the first element
// constructor sets first to null
public void SimpleLinkedList(){
this.first = null;
}
public boolean isEmpty(){
if (this.first == null) {
return true;
} else {
return false;
}
} // returns true if list is empty
// Added this method to insert a node to the beginning
public void insertFirst(int i) { //accept new values
Node newNode = new Node(i); // create a new link
newNode.next = first; // change the new link’s next reference
first = newNode; // Change first to reference the new link, where index = 0
}
public Node deleteFirst() {
Node temp = first; // reset the first reference to first.next
first = first.next; // reroute downstream
return temp; // return deleted link
}
}
class Stack {
private LinkList theList;
public LinkStack() { // constructor
theList = new LinkList();
}
public void push(int i) { // put item on top of stack
theList.insertFirst(i);
}
public long pop() { // take item from top of stack
return theList.deleteFirst();
}
public boolean isEmpty() { // true if stack is empty
return ( theList.isEmpty() );
}
public void displayStack() {
System.out.print("Stack (top-->bottom): ");
theList.displayList();
}
} // end class LinkStack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment