Implementing a Stack with a Linked List in Python

This technical problem asks the reader to write a Python class that implements a stack using a linked list. The stack should have methods for pushing an integer onto the stack, popping and returning the top element of the stack, and checking if the stack is empty.

Problem

Given a list of integers, write a Python class that implements a stack using a linked list. The stack should have the following methods:
- push(x): Push an integer x onto the stack.
- pop(): Pop and return the top element of the stack. If the stack is empty, return None.
- is_empty(): Return true if the stack is empty, and false otherwise.
Example input:
push(1)
push(2)
push(3)
Example output:
3
2
1

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class Stack:
    def __init__(self):
        self.head = None

    def push(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def pop(self):
        if self.head is None:
            return None
        else:
            data = self.head.data
            self.head = self.head.next
            return data

    def is_empty(self):
        return self.head is None

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)

print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())

A.I. Evaluation of the Solution

The candidate's solution correctly implements a stack using a linked list. The push and pop methods work as expected. The is_empty method also works as expected.

Evaluated at: 2022-11-23 08:16:30