Creation of singly linked lists

The creation of single linked list is generally divided into two main creation methods: head plug method and tail plug method.

  • Head insertion: After inserting a new node into the head node of the linked list, the final list nodes are in the reverse order of insertion (the head node does not store specific values).
  • Tail insertion: After a new node is inserted into the last node of the linked list, the final order of the linked list nodes is the same as that of the inserted nodes.

The first interpolation

1) Create a head node and maintain a head pointer (reference) to the head node; 2) newNode indicates the node to be inserted. Maintain newNode to point to the newNode. 3) case1: when the linked list is empty, that is, a newNode is inserted for the first time, point head.next to the newNode, that is, head.next = newNode; Case2: if it is not the first time a newnode is inserted, insert the newnode between head and the node pointing to head. Next = head. head.next = newNode;

The tail interpolation

1) Create a head node and maintain a head pointer (reference) to the head node; 2) newNode indicates the node to be inserted, and maintain the tail pointer indicating the end node of the list. When tail.next == null, tail indicates the end node; 3) case1: when the linked list is empty, that is, a newNode is inserted for the first time, point head.next to the newNode, that is, head.next = newNode; Case2: if it is not the first time to insert a newNode, you need to traverse the list to locate the tail node and insert the newNode after the tail node, i.e. Tail.next = newNode;