Linked List

A linked list is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of a pointer. Python does not have linked lists in its standard library. We implement the concept of linked lists using the concept of nodes as discussed in the previous chapter. We have already seen how we create a node class and how to traverse the elements of a node. In this chapter we are going to study the types of linked lists known as singly linked lists. In this type of data structure there is only one link between any two data elements. We create such a list and create additional methods to insert, update and remove elements from the list.

Creation of Linked list

A linked list is created by using the node class we studied in the last chapter. We create a Node object and create another class to use this ode object. We pass the appropriate values thorugh the node object to point the to the next data elements. The below program creates the linked list with three data elements. In the next section we will see how to traverse the linked list.

https://www.geeksforgeeks.org/linked-list-set-1-introduction/

class Node:
def init(self, data):
self.data = data
self.next = None

class LinkedList:
def init(self):
self.head = None

def push(self, new_data):  # 头插法
    new_node = Node(new_data)
    new_node.next = self.head
    self.head = new_node

def insertAfter(self, prev_node, new_data): # 在中间某个位置插入一个节点
    if prev_node is None:
        print('Prev_node must be in the LinkedList')
        return
    new_node = Node(new_data)
    new_node.next = prev_node.next
    prev_node.next = new_node

def append(self, new_data):
    new_node = Node(new_data)
    if self.head is None:
        self.head = new_node
        return
    temp = self.head
    while temp.next:
        temp = temp.next
    temp.next = new_node

def printList(self):
    temp = self.head
    while temp:
        print(temp.data)
        temp = temp.next

llist = LinkedList()
llist.append(6) # Insert 6. So linked list becomes 6->None
llist.push(7) # Insert 7 at the beginning. So linked list becomes 7->6->None
llist.push(1) # Insert 1 at the beginning. So linked list becomes 1->7->6->None
llist.append(4) # Insert 4 at the end. So linked list becomes 1->7->6->4->None
llist.insertAfter(llist.head.next, 8) # Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.printList()
"""

你可能感兴趣的:(Linked List)