Register

# CS3 Data Structures & Algorithms

## Chapter 5 Linear Structures

The linked stack implementation is quite simple. Elements are inserted and removed only from the head of the list. A header node is not used because no special-case code is required for lists of zero or one elements. Here is the complete linked stack implementation.

// Linked stack implementation
class LStack implements Stack {
private Link top;               // Pointer to first element
private int size;               // Number of elements

// Constructors
LStack() { top = null; size = 0; }
LStack(int size) { top = null; size = 0; }

// Reinitialize stack
public void clear() { top = null; size = 0; }

// Put "it" on stack
public boolean push(Object it) {
size++;
return true;
}

// Remove "it" from stack
public Object pop() {
if (top == null) return null;
Object it = top.element();
top = top.next();
size--;
return it;
}

if (top == null) return null;
}

// Return stack length
public int length() { return size; }

// Check if the stack is empty
public boolean isEmpty() { return size == 0; }
}

// Linked stack implementation
class LStack<E> implements Stack<E> {
private Link<E> top;            // Pointer to first element
private int size;               // Number of elements

// Constructors
LStack() { top = null; size = 0; }
LStack(int size) { top = null; size = 0; }

// Reinitialize stack
public void clear() { top = null; size = 0; }

// Put "it" on stack
public boolean push(E it) {
size++;
return true;
}

// Remove "it" from stack
public E pop() {
if (top == null) { return null; }
E it = top.element();
top = top.next();
size--;
return it;
}

if (top == null) { return null; }
}

// Return stack length
public int length() { return size; }

// Tell if the stack is empty
public boolean isEmpty() { return size == 0; }
}


Here is a visual representation for the linked stack.

Settings

Saving...
Server Error
Resubmit