0% found this document useful (0 votes)
10 views

CSE 220 Week 4

Uploaded by

ohidul.hossain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

CSE 220 Week 4

Uploaded by

ohidul.hossain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Data Structures

Mushtari Sadia
Linked List
Different Types of Linked Lists

Category 1 Category 2 Category 3

Non-Dummy Headed Singly Linear

Dummy Headed Doubly Circular


Non Dummy Headed

10 → 20 → 30 → 40

First node contains value 10.


Dummy Headed

DH → 10 → 20 → 30 → 40

In this linked list, DH refers dummy head


which is a node without any element. The
first item is stored after the dummy head.
Singly

10 → 20 → 30 → 40

Only contains next pointer, no


previous pointer
Doubly
10 ⇄ 20 ⇄ 30 ⇄ 40
Contains both next and previous pointer

1
class Node:
def __init__(self, e, n, p):
self.elem = e
self.next = n prev elem next
self.prev = p
Linear vs Circular
Linear: 10 → 20 → 30 → 40
Circular:
10 → 20 → 30 → 40
Dummy-headed doubly circular linked list

DH⇄ 10 ⇄ 20 ⇄ 30 ⇄ 40
Dummy-headed doubly circular linked list
class DoublyNode:

def __init__(self, elem, next, prev):

self.elem = elem

self.next = next # To store the next node’s reference.

self.prev = prev # To store the previous node’s reference.


Dummy-headed doubly circular linked list
Dummy-headed doubly circular linked list
Dummy-headed doubly circular linked list
Dummy-headed doubly circular linked list
Dummy-headed doubly circular linked list
Reasons for doubly linked list
Problem of singly linked lists:

● We have to be very careful regarding where to stop the traversal. For


example, if you want to insert at position n, then we have to stop
traversal at position n – 1. If you want to read then we stop traversal
at n. If we make one more wrong step then we cannot backtrack. You
have to restart from the head.
Reasons for doubly linked list
Reasons for doubly linked list

Some of you know about the famous mathematician and computer scientist Alan Turing. He investigated and proved many important properties
about computers. One of his most fascinating contributions is the Turing Machine that can simulate any computer. By doing so, the Turing
machine allows us to investigate the fundamental limitations and capabilities of all computers ever being built. The machine is surprisingly
simple. It has an infinite tape of symbols and a read-write head that can make one-step forward or backward on that tape in each step or
change the content of the tape cell where the head is located at that moment. The read-write head, also called the finite control, keeps track of
its current state and decides what to do based-on the symbol on the tape in its position and its state.

So what kind of list you need to implement this tape?


Practice
def move_last_to_front(linked_list ):
if linked_list .head is None or linked_list .head.next is None:
return

prev = None
current = linked_list .head

# Traverse to the last node and keep track of the previous node
while current.next:
prev = current
current = current.next

# Set the last node as the new head


prev .next = None
current .next = linked_list .head
linked_list .head = current
def intersection( list1, list2):
if list1 is None or list2 is None:
return None

intersection_list = LinkedList ()
current1 = list1.head
current2 = list2.head

while current1 and current2 :


if current1 .data == current2 .data:
Insert at last
intersection_list .add_node(current1.data)
position of
current1 = current1 .next linked list, write
current2 = current2 .next the function
elif current1 .data < current2 .data: yourself
current1 = current1 .next
else:
current2 = current2 .next

return intersection_list
def get_last_node(head):
current = head
while current.next:
current = current.next
return current

def is_palindrome(head):
left = head
right = get_last_node (head)

while left != right and right.next != left:


if left.data != right.data:
return False
left = left.next
right = right.prev

return True
def reverse(head):
current = head
while current:
temp = current.prev
current.prev = current.next
current.next = temp
current = current.prev

head = temp.prev
return head
Next Class: Quiz on linked list

Wednesday 8:00 AM
Stack
Introduction
Basic Operations
● Push(obj): adds obj to the top of the stack ("overflow" error if the stack has fixed capacity,
and is full)

● Pop: removes and returns the item from the top of the stack ("underflow" error if the stack
is empty)

● Peek: returns the item that is on the top of the stack, but does not remove it ("underflow"
error if the stack is empty)
Stack

Fixed capacity - implemented with array Unlimited capacity - implemented with linked list
Fixed Capacity Stack Example

Create (Implemented with array)

Stack of
Size 4
Push(1)

1
Push(2)

1
Push(3)

1
Push(4)
4

1
Push(5) Stack Overflow Error!

1
Peek
4

Will return 4, but will not


2 remove 4 from the stack

1
Pop
4

Will return 4 and remove


2 4 from the stack

1
Pop

1
Pop

1
Pop

1
Pop Stack Underflow Error!
import numpy as np

class Stack:
def __init__(self):
self.stack = np.zeros(4, dtype=int) Code
Implementing The
self.top = -1

def push(self, item):


if self.top == len(self.stack) - 1: Structure with
else:
print("Stack overflow")
Array
self.top += 1
self.stack[self.top] = item
def peek(self):
def pop(self): if self.top == -1:
if self.top == -1: print("Stack is empty")
print("Stack underflow") else:
else: return self.stack[self.top]
item = self.stack[self.top]
self.stack[self.top] = None
self.top -= 1
return item
stack = Stack()
stack.push(1)
Driver Code
stack.push(2) Using the
stack.push(3)
stack.push(4)
implemented
stack.push(5) structure
print(stack.peek())
print(stack.pop())
stack.pop()
print(stack.pop())
stack.pop()
stack.pop()
Fixed Capacity Stack Example
top = -1
Driver code:

Create stack = Stack()

Stack of Code running

Size 4 behind the scene:


def __init__(self):
self.stack = np.zeros(4, dtype=int)
self.top = -1
Driver code:

Push(1) top = 0
stack.push(1)

Code running
behind the scene:

def push(self, item):


if self.top == len(self.stack) - 1:
print("Stack overflow")
else:
self.top += 1
1 self.stack[self.top] = item
Driver code:

Push(2) top = 1
stack.push(2)

Code running
behind the scene:

def push(self, item):


if self.top == len(self.stack) - 1:
2
print("Stack overflow")
else:
self.top += 1
1 self.stack[self.top] = item
Driver code:

Push(3) top = 2
stack.push(3)

Code running
behind the scene:
3

def push(self, item):


if self.top == len(self.stack) - 1:
2
print("Stack overflow")
else:
self.top += 1
1 self.stack[self.top] = item
Driver code:

Push(4) top = 3
stack.push(4)
4

Code running
behind the scene:
3

def push(self, item):


if self.top == len(self.stack) - 1:
2
print("Stack overflow")
else:
self.top += 1
1 self.stack[self.top] = item
Driver code:

Push(5) top = 3
stack.push(5)
4
Stack Overflow Error!
Code running
behind the scene:
3

def push(self, item):


if self.top == len(self.stack) - 1:
2
print("Stack overflow")
else:
self.top += 1
1 self.stack[self.top] = item
Peek top = 3 Driver code:

4 print(stack.peek())

4 3 Code running
behind the scene:

def peek(self):
Will return 4, but
2 if self.top == -1:

will not remove 4 print("Stack is empty ")

from the stack else:


1 return
self.stack[self.top]
Pop top = 2 Driver code:

print(stack.pop())

4 3 Code running
behind the scene:

def pop(self):

Will return 4 and


2 if self.top == -1:
print("Stack underflow")
remove 4 from else:
the stack item = self.stack[self.top]
1 self.stack[self.top] = None
self.top -= 1
return item
Pop top = 1 Driver code:

stack.pop()

Code running
behind the scene:

def pop(self):

Will remove 3
2 if self.top == -1:
print("Stack underflow")
from the stack else:
item = self.stack[self.top]
1 self.stack[self.top] = None
self.top -= 1
return item
Pop top = 0 Driver code:

stack.pop()

Code running
behind the scene:

def pop(self):

Will remove 2 if self.top == -1:


print("Stack underflow")
from the stack else:
item = self.stack[self.top]
1 self.stack[self.top] = None
self.top -= 1
return item
Pop top = -1 Driver code:

stack.pop()

Code running
behind the scene:

def pop(self):

Will remove 1 if self.top == -1:


print("Stack underflow")
from the stack else:
item = self.stack[self.top]
self.stack[self.top] = None
self.top -= 1
return item
Pop top = -1 Driver code:

stack.pop()

Stack Underflow
Error! Code running
behind the scene:

def pop(self):
if self.top == -1:
print("Stack underflow")
else:
item = self.stack[self.top]
self.stack[self.top] = None
self.top -= 1
return item
Stack Applications
1. Call Stacks

def main:
A()

def A:
B()

def B:
print("hello world")

main()
Stack Applications Hello

2. Reverse a word
def reverse_word(word):
word = "Hello"
stack = Stack()
reversed_word = reverse_word(word)
print(reversed_word)
# Push each character of the word onto the stack
for char in word:
stack.push(char)

reversed_word = ""

# Pop each character from the stack to get the reversed word olleH
while not stack.is_empty():
reversed_word += stack.pop()

return reversed_word
Stack Applications

3. Undo

4. Browser back button

You might also like