Singly Linked List
This is a Python implementation of a singly linked list.
Usage
Singly Linked List
This is a Python implementation of a singly linked list.
Installation
Install the SingleLinkedList
package from PyPI using pip
:
pip install single-linked-list==0.0.3
then, import the SingleLinkedList
class or CicruleSingeLinkedList
from slll.slll import SingleLinkedList
from slll.csll import CicruleSingeLinkedList
Initialize a Singly Linked List
single_linked_list = SingleLinkedList()
cicrule_single_list = CicruleSingeLinkedList()
Methods
* Append
- inserts a new node at the end of the linked list.
Method:
data(any)
: The data to be stored in the new node.
single_linked_list.append(1)
single_linked_list.append(2)
cicrule_single_list.append(1)
cicrule_single_list.append(2)
* Preappend
- inserts a new node at the beginning of the linked list.
Method:
data(any)
: The data to be stored in the new node.
single_linked_list.pre_append(0)
cicrule_single_list.pre_append(0)
* Insert
- inserts a new node at the specified index in the linked list.
Method:
index(int)
: The index where the new node should be inserted.
data(any)
: The data to be stored in the new node.
single_linked_list.insert(2, 3)
cicrule_single_list.insert(2, 3)
* Find
- returns the index of the first node containing the specified data.
Method:
data(any)
: The data to search for.
index = single_linked_list.find(2)
index = cicrule_single_list.find(2)
print(index)
* Get
- returns the node at the specified index.
Method:
index(int)
: The index of the desired node.
node = single_linked_list.get(2)
node = cicrule_single_list.get(2)
print(node.data)
* Set
- updates the data of the node at the specified index.
Method:
index(int)
: The index of the node to be updated.
data(any)
: The new data to be stored in the node.
single_linked_list.set(0, 9000)
cicrule_single_list.set(0, 9000)
* Pop
- removes and returns the last node in the linked list.
Method:
last_node = single_linked_list.pop()
last_node = cicrule_single_list.pop()
print(last_node)
* Pop First
- removes and returns the first node in the linked list.
Method:
first_node = single_linked_list.pop_first()
first_node = cicrule_single_list.pop_first()
print(first_node)
* Remove
- removes the node at the specified index from the linked list.
Method:
index(int)
: The index of the node to be removed.
single_linked_list.remove(2)
cicrule_single_list.remove(2)
* Clear
- clears all nodes in the linked list.
Method:
single_linked_list.clear()
cicrule_single_list.clear()
* Get Length
- returns the current size (length) of the linked list.
Method:
length = len(single_linked_list)
length = len(cicrule_single_list)
print(length)
* Traverse and print
- traverses the linked list and prints the data of each node.
Method:
single_linked_list.traverse()
cicrule_single_list.traverse()
* String representation
- returns a string representation of the linked list.
Method:
linked_list_str