链表的理解
结点分为两部分,结点的数据和结点的引用
结点中的数据指向下一个结点的数据
图中便是 a.next = b;
b.next = null;
Node定义链表
public class Node {
int val;
Node next;
Node(int val, Node next) {
this.val = val;
this.next = next;
}
Node(int val) {
this(val, null);
}
@Override
public String toString() {
return String.format("Node{%d}", val);
}
}
MyLinkedList.java
public class MyLinkedList {
public static Node buildLinkedListHand() {
//创建一个链表
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
//1 2 3 4 5
//创建链接
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
//返回head头
return n1;
}
public static void printLinkedList(Node head) {
//打印链表
Node cur = head;
while (cur != null) {
System.out.println(cur.val);
cur = cur.next;
}
}
public static Node pushFront(Node head, int val) {
//头插
Node node = new Node(val);//创建一个要插入的结点
node.next = head;
return node;
}
public static Node popFront(Node head) {
//头删
if (head == null) {
throw new RuntimeException("空链表");
}
head = head.next;
return head;
}
public static Node pushBack(Node head, int val) {
//尾插
Node node = new Node(val);
if (head == null) {
throw new RuntimeException("空链表");
} else {
Node cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;//跳出时为最后一个结点,将最后一个结点的next改成node
return head;
}
}
public static Node popBack(Node head) {
//尾删
if (head == null) {
throw new RuntimeException("空链表");
}
if(head.next == null) {
return null;
} else {
Node cur = head;
while (cur.next.next != null) {
cur = cur.next;
}
cur.next = null;
return head;
}
}
public static void main(String[] args) {
Node head = null;
head = pushFront(head, 0);
head = pushFront(head, 1);
head = pushFront(head, 2);
head = pushFront(head, 3);
head = pushFront(head, 4);
head = pushFront(head, 5);
head = pushFront(head, 6);
printLinkedList(head);
head = popBack(head);
printLinkedList(head);
head = popFront(head);
printLinkedList(head);
head = pushFront(head,0);
printLinkedList(head);
head = pushBack(head, 8);
printLinkedList(head);
}
}
链表的重点在于理解结点的next