Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views13 pages

Intro to Linked Lists in Python

The document discusses linked lists as a data structure. It describes what a linked list is, how it is composed of nodes that link to the next node, and examples of implementing a linked list in Python including defining Node and LinkedList classes and methods like add, remove, search, and print.

Uploaded by

Maxi Brad
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)
14 views13 pages

Intro to Linked Lists in Python

The document discusses linked lists as a data structure. It describes what a linked list is, how it is composed of nodes that link to the next node, and examples of implementing a linked list in Python including defining Node and LinkedList classes and methods like add, remove, search, and print.

Uploaded by

Maxi Brad
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/ 13

Computer Science 1001

Lecture 32

Lecture Outline

• Linked lists

– CS1001 Lecture 32 –
Data structures

• A data structure is a way to store a collection of


data.

• Python provides several built-in collection classes.


For example, lists. There are also sets, tuples, and
dictionaries.

• A list is a collection of elements that can be accessed


via an integer index. We can also loop over elements
of a list with a for loop.

• We will now consider creating a data structure,


called a linked list, to store a collection of objects.

– CS1001 Lecture 32 – 1
Linked List

• A linked list is a data structure consisting of a


collection of objects arranged one after another,
akin to links of a chain.
2 5 12 15
TOP

• Elements of the list need not be stored contiguously


in memory.

• Each element of a linked list is referred to as a node.

• A node contains space to hold the data, as well as


a link.

• The link is a reference that points to (or refers to)


the next element in the list.

• Note that we must have a way to refer to the start


of the list, as well as a way to indicate the end of
the list.

– CS1001 Lecture 32 – 2
Example: Linked List

• To create a linked list we must first define what a


node of the list looks like. We can define a node in
Python (including accessor and mutator methods)
as follows:
class Node:
def __init__(self,initdata):
self._data = initdata
self._next = None

def getData(self):
return self._data

def getNext(self):
return self._next

def setData(self,newdata):
self._data = newdata

def setNext(self,newnext):
self._next = newnext

• A Node can be created by providing an initial data


value:
n1 = Node(42)

– CS1001 Lecture 32 – 3
Example: Linked List

• Note that None is used to initialize the link element


of the Node, which indicates that there is no
subsequent node in the list.

• If we create multiple nodes, as in:

n1 = Node(42)
n2 = Node(35)
n3 = Node(98)

we have create 3 separate Node objects that are not


linked together into a list of objects.

• We could link the Nodes together by setting the


next field of a Node. For example,

n1.setNext(n2)
n2.setNext(n3)

• To make list management easier we will define a


LinkedList class.

– CS1001 Lecture 32 – 4
Example: Linked List

• A linked list must maintain a reference to the start


of the list. It is also convenient to store the size of
the list as an instance variable.

class LinkedList:
def __init__(self):
self._top = None
self._size = 0

def getSize(self):
return self._size

def isEmpty(self):
return self._top == None

• We want to be able to add nodes to the linked list,


for which we provide an add method:

def add(self,value):
# Add node to beginning of list
temp = Node(value)
temp.setNext(self._top)
self._top = temp
self._size += 1

– CS1001 Lecture 32 – 5
Example: Linked List

• We can now create a LinkedList and add Nodes.


For example:

llst = LinkedList()
llst.add(42)
llst.add(35)
llst.add(98)
llst.add(77)

• To display the current status of the linked list, we


will provide a printList method:

def printList(self):
print("List: ",end="")
current = self._top
while current != None:
print(current.getData(),end=" ")
current = current.getNext()
print()

With the linked list created above, we have:

List: 77 98 35 42

– CS1001 Lecture 32 – 6
Example: Linked List

• Now, suppose we want to search a linked list for a


node with a particular value.

• This requires us to traverse the list, starting at the


top node:

def search(self,value):
current = self._top
while current != None:
if current.getData() == value:
return True
else: # move to next node in list
current = current.getNext()
return False

• Here we are using current to refer to each Node


as we move through the list.

– CS1001 Lecture 32 – 7
Example: Linked List

• We may also want to remove nodes from the list,


for which we provide a remove method:

def remove(self,value):
# Remove node with self._data = value
current = self._top
previous = None # node prior to node to be removed
found = False
while current != None and not found:
if current.getData() == value:
found = True
else: # move to next node in list
previous = current
current = current.getNext()

if not found:
return

# Remove the node located above (current)


if previous == None: # top element to be removed
self._top = current.getNext()
else: # change reference to next node in previous
previous.setNext(current.getNext())
self._size -= 1

– CS1001 Lecture 32 – 8
Example: Linked List
• A main function to test our current functionality:
def main():
llst = LinkedList()
llst.add(42)
llst.add(35)
llst.add(98)
llst.add(77)
llst.printList()
print("Size:",llst.getSize())
print("Value 25 present?: ",llst.search(25))
print("Value 98 present?: ",llst.search(98))
print("Removing 45...")
llst.remove(45)
llst.printList()
print("Removing 77...")
llst.remove(77)
llst.printList()
print("Value 77 present?: ",llst.search(77))

Output:
List: 77 98 35 42
Size: 4
Value 25 present?: False
Value 98 present?: True
Removing 45...
List: 77 98 35 42
Removing 77...
List: 98 35 42
Value 77 present?: False

– CS1001 Lecture 32 – 9
Example: Linked List
class Node:
def __init__(self,initdata):
self._data = initdata
self._next = None

def getData(self):
return self._data

def getNext(self):
return self._next

def setData(self,newdata):
self._data = newdata

def setNext(self,newnext):
self._next = newnext

class LinkedList:
def __init__(self):
self._top = None
self._size = 0

def getSize(self):
return self._size

def isEmpty(self):
return self._top == None

def add(self,value):
# Add node to beginning of list

– CS1001 Lecture 32 – 10
temp = Node(value)
temp.setNext(self._top)
self._top = temp
self._size += 1

def remove(self,value):
# Remove node with self._data = value
current = self._top
previous = None # node prior to node to be removed
found = False
while current != None and not found:
if current.getData() == value:
found = True
else: # move to next node in list
previous = current
current = current.getNext()

if not found:
return

# Remove the node located above (current)


if previous == None: # top element to be removed
self._top = current.getNext()
else: # change reference to next node in previous
previous.setNext(current.getNext())
self._size -= 1

def search(self,value):
current = self._top
while current != None:
if current.getData() == value:
return True

– CS1001 Lecture 32 – 11
else: # move to next node in list
current = current.getNext()
return False

def printList(self):
print("List: ",end="")
current = self._top
while current != None:
print(current.getData(),end=" ")
current = current.getNext()
print()

– CS1001 Lecture 32 – 12

You might also like