算法通关村第一关-链表青铜挑战笔记(单链表)
链表的定义
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
//这个一般作用不大,写了更规范
next = null;
}
链表初始化
private static ListNode init(int arr[]) {
ListNode head = null, cur = null;
for (int i = 0; i < arr.length; i++) {
ListNode newNode = new ListNode(arr[i]);
newNode.next = null;
if (i == 0) {
head = newNode;
cur = newNode;
} else {
cur.next = newNode;
cur = newNode;
}
}
return head;
}
链表遍历
public static int getLength(ListNode head) {
int length = 0;
ListNode node = head;
while (node != null) {
length ++;
node = node.next;
}
return length;
}
链表的插入
单链表的插入需要考虑三种情况:头部,中部和尾部
(1)在链表头部插入
newNode.next = head;
head = newNode;
return head;
(2)在链表中部插入
在中部插入首先要遍历找到要插入的位置,找到该位置后会出现一个问题:前驱结点无法获取
因此我们需要在目标的前一个位置停下
ListNode preNode = head;
int count = 1;
//寻找带插入结点的前一个结点
while (count < position - 1) {
preNode = preNode.next;
count++;
}
//两步顺序不能颠倒
newNode.next = preNode.next;
preNode.next = newNode;
(3)在链表尾部插入
完整代码
/**
* 链表插入
*
* @param head 链表头节点
* @param newNode 待插入节点
* @param position 待插入位置
* @return 插入后得到的链表头节点
*/
public static ListNode insertNode(ListNode head, ListNode newNode, int position) {
// 需要判空,否则后面可能会有空指针异常
if (ListNode == null) {
return newNode;
}
//越界判断
int size = getLength(head);
if (position > size + 1 || position < 1) {
System.out.println("位置参数越界");
return head;
}
//在链表头部插入
if (position == 1) {
newNode.next = head;
head = newNode;
return head;
}
//在链表中部插入
ListNode preNode = head;
int count = 1;
//寻找带插入结点的前一个结点
while (count < position - 1) {
preNode = preNode.next;
count++;
}
newNode.next = preNode.next;
preNode.next = newNode;
return head;
}
链表的删除
链表的删除同样也需要考虑三种情况
完整代码
public static ListNode deleteNode(ListNode head, int position) {
if (head == null) {
return null;
}
int size = getLength(head);
if (position > size || position <= 0) {
System.out.println("输入的参数有误");
return head;
}
if (position == 1) {
return head.next;
}
ListNode preNode = head;
int count = 1;
while (count < position - 1) {
preNode = preNode.next;
count++;
Node curNode = preNode.next;
preNode.next = curNode.next;
}
return head;
}