algoritmauzmanı
Sign in
TREN
4.2Stack with a Linked List
Lesson 4.2.4

Peek: looking at the top

Sometimes you want to know what is on top without taking it off. does that: it returns the value of the node points to and leaves the stack alone. In the linked-list version this means reading the data field of the first node.

What you will learn
  • How peek differs from pop
  • What happens when you peek at an empty stack
  • How peek is written in C, Java and Python, and why it is
4 minTime O(1)Memory O(1)C · Java · Python

1Idea

Peek has two steps. First the stack is checked for being empty; if it is, there is no top to look at and that is an . Otherwise top->data is read and returned.

Unlike pop, top stays where it is. No node is allocated, no node is freed and no link changes. If you peek twice in a row you get the same value twice.

In C the value comes back through a parameter (int* value), as in pop, and the function returns success as a bool. That way an empty stack is never confused with a stack that really has 0 on top.

2Step by step

The drawing peeks at a stack holding 30, 20 and 10. At each step the matching line of code lights up.

NULL30?0x2c1020?0x1a9010?0x1a40top
  1. Start. points to 30.
  2. top is not NULL, so the stack is not empty.
  3. The value of the top node, 30, is read and handed to the caller.
  4. The stack is unchanged: 30 is still on top. In C the function returns true.

struct Node {    int data;    struct Node* next;}; struct Stack {    struct Node* top;}; bool peek(struct Stack* s, int* value) {    if (s->top == NULL) return false;  // empty stack    *value = s->top->data;    return true;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class LinkedStack {    Node top = null;     int peek() {        if (top == null) throw new IllegalStateException("stack is empty");        return top.data;  // the stack does not change    }}
class Node:    def __init__(self, data):        self.data = data        self.next = None class LinkedStack:    def __init__(self):        self.top = None     def peek(self):        if self.top is None:            raise IndexError("stack is empty")        return self.top.data  # the stack does not change

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1)

One comparison and one read; the size of the stack does not matter.

Memory
O(1)

No extra memory is used.

The array version reads items[top] and the linked-list version reads top->data. Both are .

4Common mistake

The most common mistake is skipping the empty check:

bool peek(struct Stack* s, int* value) {    *value = s->top->data;  // top may be NULL    return true;}

When the stack is empty s->top is and s->top->data tries to read through a NULL pointer; the program crashes. Check s->top == NULL first.

5Try it

A stack holds 30, 20, 10 from top to bottom. You peek, then pop, then peek again. What do the two peeks return?

Show the answer

The answer is B. The first peek returns 30 and the stack does not change. Pop removes 30 and top moves to 20. The second peek returns 20.

What is the complexity of peek on a linked-list stack?

Show the answer

The answer is A. The top is the first node of the list and top points straight at it. There is no need to walk the list.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.