What is a linked list?
The linked list is a relatively common data structure . The linked list is connected by multiple nodes with the same structure. Each node is divided into a data field and a pointer field . The data field stores data, and the pointer field stores the address of the next node.
Basics and construction methods of singly linked lists
Single linked list structure diagram
Single list creation
public class Node {
public int val;
public Node next;
Node(int x) {
val = x;
next = null;
}
}
Single list initialization
static Node initLinkedList(int[] array) {
//初始化head 都为null 保证内存地址一样,,
Node head = null;
Node currentNode = null;
for (int i = 0; i < array.length; i++) {
Node newNode = new Node(array[i]);
newNode.next = null;
if (i == 0) {
//初始化头节点
head = newNode;
currentNode = newNode;
} else {
//讲当前的节点的指针指向下一个节点
currentNode.next = newNode;
//将下一个节点赋值给当前节点
currentNode = newNode;
}
}
return head;
}
Get the length of the list
public static int getListLength(Node head){
int length=0;
Node node = head;
while (node != null ){
length++;
node=node.next;
}
return length;
}
Insert element into linked list
(1) Insert at the head of the linked list
- Create insertion node newNode
- newNode.next = head
- head = newNode
(2) Insert in the middle of the linked list
public static Node insertNode(Node head, Node nodeInsert, int position) {
if (head == null) {
return nodeInsert;
}
int size = getLength(head);
if (position > size + 1 || position < 1) {
return head;
}
if (position == 1) {
nodeInsert.next = head
head = nodeInsert;
return head;
}
Node pNode = head;
int count = 1;
while (count < position - 1) {
pNode = pNode.next;
count++;
}
nodeInsert.next = pNode.next;
pNode.next = nodeInsert;
return head;
}
(3) Insert at the end of the linked list
Linked list deletion
(1) Delete the header node
- Let the head node point to the next element
head = head.next
(2) Delete intermediate nodes
(3) Delete the end node
public static Node deleteNode(Node head, int position) {
if (head == null) {
return null;
}
int size = getLength(head);
if (position > size || position <= 0) {
return head;
}
if (position == 1) {
return head.next;
}
Node preNode = head;
int count = 1;
while (count < position) {
preNode = preNode.next;
count++;
Node curNode = preNode.next;
preNode.next = curNode.next;
}
return head;
}
Definition of doubly linked list
class DoubleNode {
public int data; //数据域
public DoubleNode next; //指向下一个结点
public DoubleNode prev;
public DoubleNode(int data) {
this.data = data;
}
//打印结点的数据域
public void displayNode() {
System.out.print("{" + data + "} ");
}
}
Structure diagram: