1 单链表的基础与构造方法
学习所有数据结构的基础:创建 + 增删改查;我认为还需要会调用一些常用API;
1.1 链表的内部结构
链表由 数据 + 指针 构成,数据存放值,指针指向下一个节点,连接链表。
规范的链表定义:
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
leetcode中定义:
public class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x;
//这个一般作用不大,写了会更加规范
next = null;
}
}
ListNode listnode=new ListNode(1);
1.2 单链表的遍历
链表的所有操作一定是从头逐个向后访问,再进行其他操作的。
public static int getListLength(Node head) {
int length = 0;
Node node = head;
while (node != null) {
length++;
node = node.next;
}
return length;
}
1.3 单链表的插入
链表的插入分为三种情况:首部、中部、尾部。
(1)头部:
(2)中部:
(3)尾部:
/**
* 链表插入
* @param head 链表头节点
* @param nodeInsert 待插入节点
* @param position 待插入位置,从1开始
* @return 插入后得到的链表头节点
*/
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 单链表的删除
同样分为头部、中部、尾部
(1)头部:
(2)中部:
(3)尾部:
/**
* 删除节点
* @param head 链表头节点
* @param position 删除节点位置,取值从1开始
* @return 删除后的链表头节点
*/
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;
}