# Node class for a linked list
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Linked List class
class LinkedList:
def __init__(self):
self.head = None
# Create a new linked list based on the data
def create(self, data):
if not data:
return
self.head = ListNode(data[0])
cur = self.head
for i in range(1, len(data)):
node = ListNode(data[i])
cur.next = node
cur = cur.next
# Get the length of the linked list
def length(self):
count = 0
cur = self.head
while cur:
count += 1
cur = cur.next
return count
# Insert an element at the front of the linked list
def insertFront(self, val):
node = ListNode(val)
node.next = self.head
self.head = node
# Insert an element at the rear of the linked list
def insertRear(self, val):
node = ListNode(val)
if not self.head:
self.head = node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = node
# Insert an element at a specific index
def insertInside(self, index, val):
if index < 0:
return 'Error'
if index == 0:
self.insertFront(val)
return
count = 0
cur = self.head
while cur and count < index - 1:
count += 1
cur = cur.next
if not cur:
return 'Error'
node = ListNode(val)
node.next = cur.next
cur.next = node
# Modify an element at a specific index
def change(self, index, val):
count = 0
cur = self.head
while cur and count < index:
count += 1
cur = cur.next
if not cur:
return 'Error'
cur.val = val
# Remove an element from the front of the linked list
def removeFront(self):
if self.head:
self.head = self.head.next
# Remove an element from a specific index
def removeInside(self, index):
if index < 0:
return 'Error'
if index == 0:
self.removeFront()
return
count = 0
cur = self.head
while cur.next and count < index - 1:
count += 1
cur = cur.next
if not cur:
return 'Error'
if cur.next:
del_node = cur.next
cur.next = del_node.next
def main():
# Create a new linked list
my_linked_list = LinkedList()
# Create a linked list from a list of values
data = [1, 2, 3, 4]
my_linked_list.create(data)
# Print the initial linked list
cur = my_linked_list.head
while cur:
print(cur.val, end=" -> ")
cur = cur.next
print("None")
# Insert an element at the front of the linked list
my_linked_list.insertFront(0)
# Insert an element at the rear of the linked list
my_linked_list.insertRear(5)
# Insert an element at a specific index
my_linked_list.insertInside(3, 100) # Insert 100 at index 3
# Change the value of an element at a specific index
my_linked_list.change(2, 200) # Change the value at index 2 to 200
# Remove an element from the front of the linked list
my_linked_list.removeFront()
# Remove an element from a specific index
my_linked_list.removeInside(4) # Remove the element at index 4
# Print the modified linked list
cur = my_linked_list.head
while cur:
print(cur.val, end=" -> ")
cur = cur.next
print("None")
if __name__ == "__main__":
main()
结果:
1 -> 2 -> 3 -> 4 -> None
1 -> 200 -> 100 -> 3 -> 5 -> None