This is a Python implementation of a singly linked list.
This is a Python implementation of a singly linked list.
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()
- inserts a new node at the end of the linked list.
- append(data)
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)
- inserts a new node at the beginning of the linked list.
- pre_append(data)
data(any)
: The data to be stored in the new node.
single_linked_list.pre_append(0)
cicrule_single_list.pre_append(0)
- inserts a new node at the specified index in the linked list.
- insert(data, index)
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)
- returns the index of the first node containing the specified data.
- find(data)
data(any)
: The data to search for.
index = single_linked_list.find(2)
index = cicrule_single_list.find(2)
print(index) # Output: 1
- returns the node at the specified index.
- get(index)
index(int)
: The index of the desired node.
node = single_linked_list.get(2)
node = cicrule_single_list.get(2)
print(node.data) # Output: 3
- updates the data of the node at the specified index.
- set(index, data)
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)
- removes and returns the last node in the linked list.
- pop()
last_node = single_linked_list.pop()
last_node = cicrule_single_list.pop()
print(last_node) # Output: 3
- removes and returns the first node in the linked list.
- pop_first()
first_node = single_linked_list.pop_first()
first_node = cicrule_single_list.pop_first()
print(first_node) # Output: 0
- removes the node at the specified index from the linked list.
- remove(index)
index(int)
: The index of the node to be removed.
single_linked_list.remove(2)
cicrule_single_list.remove(2)
- clears all nodes in the linked list.
- clear()
single_linked_list.clear()
cicrule_single_list.clear()
- returns the current size (length) of the linked list.
- len()
length = len(single_linked_list)
length = len(cicrule_single_list)
print(length) # Output: 1
- traverses the linked list and prints the data of each node.
- traverse()
single_linked_list.traverse()
cicrule_single_list.traverse()
# Output: 0 -> 1 -> 3
- returns a string representation of the linked list.
- str()
linked_list_str