Skip to content

[WIP] Added Stacks Using Linked List #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 11 commits into from
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ htmlcov
*~
__pycache__/
.pytest_cache/
build/
dist/

# Backup Files #
################
Expand Down
2 changes: 1 addition & 1 deletion CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ appearance, race, religion, or sexual identity and orientation.
## Our Standards

Examples of behavior that contributes to creating a positive environment
include:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't make changes to this file.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address this.



* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from pydatastructs import SinglyLinkedList

__all__ = ["Linked_Stacks"]
class Linked_Stacks:

# A class to implement Stacks Built over Singly Linked Lists

def __init__(self):
self.sll = SinglyLinkedList()
self.top = self.sll.head

def push(self,data):
self.sll.append(data)
if self.top is None:
self.top = self.sll.head
return self

def pop(self):
if self.top is not None:
self.data = self.top.data
self.top = self.top.next
return self.data

def peek(self):
return self.top.data
189 changes: 189 additions & 0 deletions build/lib/pydatastructs/miscellaneous_data_structures/stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
from pydatastructs.linear_data_structures import DynamicOneDimensionalArray
from pydatastructs.utils.misc_util import _check_type, NoneType
from copy import deepcopy as dc
from pydatastructs import DoublyLinkedList

__all__ = [
'Stack'
]

class Stack(object):
"""Representation of stack data structure

Parameters
==========

implementation : str
Implementation to be used for stack.
By default, 'array'
Currently only supports 'array'
implementation.
items : list/tuple
Optional, by default, None
The inital items in the stack.
For array implementation.
dtype : A valid python type
Optional, by default NoneType if item
is None, otherwise takes the data
type of DynamicOneDimensionalArray
For array implementation.

Examples
========

>>> from pydatastructs import Stack
>>> s = Stack()
>>> s.push(1)
>>> s.push(2)
>>> s.push(3)
>>> str(s)
'[1, 2, 3]'
>>> s.pop()
3

References
==========

.. [1] https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
"""

def __new__(cls, implementation='array', **kwargs):
if implementation == 'array':
return ArrayStack(
kwargs.get('items', None),
kwargs.get('dtype', int))

elif implementation == "ll":
return Linked_Stacks()

raise NotImplementedError(
"%s hasn't been implemented yet."%(implementation))


def push(self, *args, **kwargs):
raise NotImplementedError(
"This is an abstract method.")

def pop(self, *args, **kwargs):
raise NotImplementedError(
"This is an abstract method.")

@property
def is_empty(self):
return None

@property
def peek(self):
return None


class ArrayStack(Stack):

__slots__ = ['items']

def __new__(cls, items=None, dtype=NoneType):
if items is None:
items = DynamicOneDimensionalArray(dtype, 0)
else:
items = DynamicOneDimensionalArray(dtype, items)
obj = object.__new__(cls)
obj.items = items
return obj

def push(self, x):
if self.is_empty:
self.items._dtype = type(x)
self.items.append(x)

def pop(self):
if self.is_empty:
raise ValueError("Stack is empty")

top_element = dc(self.items[self.items._last_pos_filled])
self.items.delete(self.items._last_pos_filled)
return top_element

@property
def is_empty(self):
return self.items._last_pos_filled == -1

@property
def peek(self):
return self.items[self.items._last_pos_filled]

def __str__(self):
"""
Used for printing.
"""
return str(self.items._data)

class Linked_Stacks(Stack):

"""Representation of Stack Data Structure using Doubly Linked List
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, we can use SinglyLinkedList for stacks.

Methods
===========
push :
A normal push operation to the Stack

pop :
Delete the top most element from the stack
Returns the value of top element

peek :
returns the value of top element

is_empty :
Checks for whether a Stack is been empty or not
Return True if empty else False

__str__ :
Used for Printing the Stack

"""
__slots__ = ["dll"]
def __new__(cls):
dll = DoublyLinkedList()
obj = object.__new__(cls)
obj.dll = dll
obj.top = dll.head
return obj


def push(self,data):
self.dll.append(data)
if self.top is None:
self.top = self.dll.head
self.top = self.top.next

def pop(self):
if not self.is_empty:
self.data = self.top.data
self.top = self.top.prev
return self.data
else:
raise ValueError("Stack is Empty")

@property
def is_empty(self):
if self.top is None:
return 1
return 0
return self.top is None


@property
def peek(self):
if self.top is not None:
return self.top.data
raise ValueError("Stack is Empty")

def __str__(self):
"Used for Printing the Stack"
iterator = self.top
output = ""
while iterator is not None:
#print(iterator.data)
output+=str(iterator.data)+"\n"
iterator = iterator.prev
output = output[:-1]
return output
Binary file added dist/pydatastructs-0.0.0-py3.8.egg
Binary file not shown.
78 changes: 78 additions & 0 deletions pydatastructs/miscellaneous_data_structures/stack.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from pydatastructs.linear_data_structures import DynamicOneDimensionalArray
from pydatastructs.utils.misc_util import _check_type, NoneType
from copy import deepcopy as dc
from pydatastructs import DoublyLinkedList

__all__ = [
'Stack'
Expand Down Expand Up @@ -51,9 +52,14 @@ def __new__(cls, implementation='array', **kwargs):
return ArrayStack(
kwargs.get('items', None),
kwargs.get('dtype', int))

elif implementation == "ll":
return Linked_Stacks()

raise NotImplementedError(
"%s hasn't been implemented yet."%(implementation))


def push(self, *args, **kwargs):
raise NotImplementedError(
"This is an abstract method.")
Expand All @@ -70,6 +76,7 @@ def is_empty(self):
def peek(self):
return None


class ArrayStack(Stack):

__slots__ = ['items']
Expand Down Expand Up @@ -109,3 +116,74 @@ def __str__(self):
Used for printing.
"""
return str(self.items._data)

class LinkedListStack(Stack):

"""Representation of Stack Data Structure using Doubly Linked List
Methods
===========
push :
A normal push operation to the Stack

pop :
Delete the top most element from the stack
Returns the value of top element

peek :
returns the value of top element

is_empty :
Checks for whether a Stack is been empty or not
Return True if empty else False

__str__ :
Used for Printing the Stack

"""
__slots__ = ["dll"]
def __new__(cls):
dll = DoublyLinkedList()
obj = object.__new__(cls)
obj.dll = dll
obj.top = dll.head
return obj


def push(self,data):
self.dll.append(data)
if self.top is None:
self.top = self.dll.head
self.top = self.top.next

def pop(self):
if not self.is_empty:
self.data = self.top.data
self.top = self.top.prev
return self.data
else:
raise ValueError

@property
def is_empty(self):
if self.top is None:
return 1
return 0
return self.top is None


@property
def peek(self):
if self.top is not None:
return self.top.data
raise ValueError

def __str__(self):
"Used for Printing the Stack"
iterator = self.top
output = ""
while iterator is not None:
#print(iterator.data)
output+=str(iterator.data)+"\n"
iterator = iterator.prev
output = output[:-1]
return output