1.链表的原理
属于一种线性表
1.元素和元素直接有相对顺序的
2.有头部/尾部
3.prev / cur / next
不同于顺序表:
逻辑上存在线性结构,但不保证物理满足该次序
链表的结点定义:
public class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
@Override
public String toString() {
return "Node{" + val + "}";
}
}
创建一个 [1 3 2 6] 的链表 :
Node n1 = new Node(1);
Node n3 = new Node(3);
Node n2 = new Node(2);
Node n6 = new Node(6);
n1.next = n3;
n3.next = n2;
n2.next = n6;
n6.next = null;
Node head = n1 ;
头插
public static Node pushFront(Node head, int val){
Node node = new Node(val);
node.next = head ;
return node ;
}
头删
假定不为空结点
public static Node popFront(Node head) {
return head.next;
}
尾插
private static Node pushBack(Node head, int v) {
if (head == null) {
Node node = new Node(v);
return node;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
Node node = new Node(v);
last.next = node;
return head; }
尾删
private static Node popBack(Node head) {
// head != null
if (head.next == null) {
return null;
} else {
Node last = head;
while (last.next.next != null) {
last = last.next;
}
// last 是最后一个结点
last.next = null;
return head;
}
}