Linklist with all methods
# Create nodes using dictionaries
node1 = {"data": 10, "next": None}
node2 = {"data": 20, "next": None}
node3 = {"data": 30, "next": None}
# Link the nodes
node1["next"] = node2
node2["next"] = node3
head = node1
# 1. Display Linked List
print("Linked List:")
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
# 2. Insert at Beginning
new_node = {"data": 5, "next": head}
head = new_node
print("\nAfter Insert at Beginning:")
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
# 3. Insert at End
new_node = {"data": 40, "next": None}
current = head
while current["next"] is not None:
current = current["next"]
current["next"] = new_node
print("\nAfter Insert at End:")
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
# 4. Insert after a specific value
new_node = {"data": 25, "next": None}
current = head
while current is not None:
if current["data"] == 20:
new_node["next"] = current["next"]
current["next"] = new_node
break
current = current["next"]
print("\nAfter Insert 25 after 20:")
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
# 5. Search an element
search = 30
current = head
found = False
while current is not None:
if current["data"] == search:
found = True
break
current = current["next"]
if found:
print("\n30 Found")
else:
print("\n30 Not Found")
# 6. Count Nodes
count = 0
current = head
while current is not None:
count = count + 1
current = current["next"]
print("Total Nodes:", count)
# 7. Delete from Beginning
head = head["next"]
print("\nAfter Delete from Beginning:")
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
# 8. Delete from End
current = head
while current["next"]["next"] is not None:
current = current["next"]
current["next"] = None
print("\nAfter Delete from End:")
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
# 9. Delete a specific value
delete_value = 25
current = head
while current["next"] is not None:
if current["next"]["data"] == delete_value:
current["next"] = current["next"]["next"]
break
current = current["next"]
print("\nAfter Delete 25:")
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
-----------------------------
Output
Linked List:
10 -> 20 -> 30 -> None
After Insert at Beginning:
5 -> 10 -> 20 -> 30 -> None
After Insert at End:
5 -> 10 -> 20 -> 30 -> 40 -> None
After Insert 25 after 20:
5 -> 10 -> 20 -> 25 -> 30 -> 40 -> None
30 Found
Total Nodes: 6
After Delete from Beginning:
10 -> 20 -> 25 -> 30 -> 40 -> None
After Delete from End:
10 -> 20 -> 25 -> 30 -> None
After Delete 25:
10 -> 20 -> 30 -> None
Comments
Post a Comment