Before you use Python to write a linked list, you need to understand the nature of variable storage in Python: variables themselves are stored as an address, and to exchange their values is to change their points. Based on this point, the pointer problem in the linked list can be solved.
One way linked list: also called single linked list. It is the simplest one in the linked list. It is composed of nodes. Each node contains two fields, an information field (element field) and a link field. The link points to the next node in the list, and the link field of the last node points to a null value.
Node implementation:
class Node(object): """node""" def __init__(self, val=None): self.val = val # Storage elements self.next = None # Point to next node
Common operations of single chain table:
- is_empty(): determines whether the linked list is empty. If it is empty, it returns True. Otherwise, it returns False.
- length(): returns the length of the linked list.
- print(): traverses the linked list and prints the elements in it.
- add(item): add an element to the chain header.
- append(item): add elements to the end of the list.
- insert(pos, item): adds an element to the specified location.
- remove(item): delete a specified element. If the deletion is successful, the element will be returned. Otherwise, None will be returned.
- search(item): find whether an element exists, return its index if it exists, otherwise return - 1.
Python code:
class SingleLinkList(object): """Single linked list""" def __init__(self, node=None): self.__head = node def is_empty(self): """Judge whether it is empty""" return self.__head==None def length(self): """Return chain length""" count = 0 # cur: cursors are used to move traversal nodes cur = self.__head while cur != None: count += 1 cur = cur.next return count def print(self): """Traverse the entire list""" cur = self.__head while cur != None: print(cur.val, end=" ") cur = cur.next print("") def add(self, item): """Add elements to the head""" node = Node(item) node.next = self.__head self.__head = node def append(self, item): """Add elements at the end""" node = Node(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node def insert(self, pos, item): """Add element at specified location""" if pos < 0: self.add(item) elif pos > self.length()-1: self.append(item) else: node = Node(item) cur = self.__head count = 0 while count < pos-1: count += 1 cur = cur.next node.next = cur.next cur.next = node def remove(self, item): """Delete an element""" pre = None cur = self.__head while cur != None: if cur.val == item: if cur == self.__head: self.__head = cur.next else: pre.next = cur.next return item else: pre = cur cur = cur.next return None def search(self, item): """Find whether the node exists""" count = 0 cur = self.__head while cur.next != None: if cur.val == item: return count cur = cur.next count += 1 return -1