川崎のシステム開発・アプリ開発・Web制作

Linked Lists in Python

What is linked list

A linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which together represent a sequence.

A node has two different fields :
– Data contains the valueto be stored in the node
– Next contains a reference to point to the next node on the list
Every linked list have first node called the Head. The Head used as the starting point for any iteration through the list. The last node must have its next reference pointing to None to determine the end of the list.

How to create a linked list

First, create a class to represent first node of your linked list : the head

class LinkedList:
def init(self):
self.head = None


Next, create a class to represent next node :

class Node:
def init(self, data):
self.data = data
self.next = None


Then start create a linked list :

linked_list = LinkedList()
linked_list
--> None


first_node = Node("a")
linked_list.head = first_node
linked_list
--> a -> None


second_node = Node("b")
third_node = Node("c")
first_node.next = second_node
second_node.next = third_node
linked_list
--> a -> b -> c -> None




この記事を書いた人

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です