1.1 什么是单链表
- 节点相互链接
- 每个节点最多一个后继节点
1.2常用的构造方法
public class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x; //节点参数
next = null; //下一个节点
}
}
ListNode listnode=new ListNode(1);
1.3链表节点的插入
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;
// 这里可以直接 return nodeInsert;还可以这么写:
head = nodeInsert;
return head;
}
Node pNode = head;
int count = 1;
//这里position被上面的size被限制住了,不用考虑pNode=null
while (count < position - 1) {
pNode = pNode.next;
count++;
}
nodeInsert.next = pNode.next;
pNode.next = nodeInsert;
return head;
}
个人理解:在这段代码中,可以了解到对于一个节点的插入,最重要的是在中间插入时,先获取需要插入的位置的后面一部分的链表,否则会造成当前位置节点后方链接消失。
1.4删除节点
public static Node deleteNode(Node head, int position) {
if (head == null) {
return null;
}
int size = getListLength(head);
//思考一下,这里为什么是size,而不是size+1
if (position > size || position <1) {
System.out.println("输入的参数有误");
return head;
}
if (position == 1) {
//curNode就是链表的新head
return head.next;
} else {
Node preNode = head;
int count = 1;
while (count < position - 1) {
preNode = preNode.next;
count++;
}
Node curNode = preNode.next;
preNode.next = curNode.next;
}
return head;
}