1.创建链表
多节点链成,每节点最多有1个后继,尾节点无后继
头节点:第一个节点,通过它,往后遍历。通常使用带头节点的单链表
1.1节点
值+后继
public class Node {
public int val;
public Node next;
Node(int x) {
val = x;
next = null;
}
}
树节点:
public class TreeNode {
public int val;
//二叉树
// public TreeNode left;
// public TreeNode right;
//n叉树
public List<TreeNode> children;
}
1.2 法一:
private static Node initLinkedList(int[] a) {
Node head = null;
Node cur = null;
Node newNode5 = new Node(a[5]);
Node newNode4 = new Node(a[4]);
Node newNode3 = new Node(a[3]);
Node newNode2 = new Node(a[2]);
Node newNode1 = new Node(a[1]);
Node newNode0 = new Node(a[0]);
head = cur = newNode0;
newNode0.next = newNode1;
newNode1.next = newNode2;
newNode2.next = newNode3;
newNode3.next = newNode4;
newNode4.next = newNode5;
return head;
}
1.3 法二:
private static Node initLinkedList(int[] array) {
Node head = null, cur = null;
for (int i = 0; i < array.length; i++) {
Node newNode = new Node(array[i]);
newNode.next = null;
if (i == 0) {
head = newNode;
cur = newNode;
} else {
cur.next = newNode;
cur = newNode;
}
}
return head;
}
2.插入链表
2.1头插:
重点:newNode.next = head ,head = newNode
2.2中插:
重点:newNode.next = cur.next ,cur.next = newNode
2.3尾插:
2.4代码:
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) {
System.out.println("位置参数越界");
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;
}