1.Java是如何构造出链表的
在LeetCode中算法题中创建链表的常用方式:
public class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x;
next = null; //这个一般作用不大,写了会更加规范
}
}
ListNode listnode=new ListNode(1);
这里的val就是当前结点的值,next指向下一个结点。因为两个变量都是public 的,创建对象后能直接使用listnode.val 和listnode.next来操作。
2.链表增加元素-单链表的插入
(1) 在链表的表头插入
- 链表表头插入新结点:
创建一个新结点newNode,
连接到原来的链表上:newNode.next=head,
head需要重新指向表头:head=newNode
(2)在链表中间插入
必须先遍历找到要插入的位置,然后将当前位置接入到前驱结点和后继结点之间,但是如果真的到了要插入的位置,之后我们却不能获得前驱结点了。为此,我们要在目标结点的前一个位置停下来。
✨例如:
如果要在node7的前面插入,当cur.next=node7的时候停下,
然后先:newNode.next=node15.next(虚线),
再:node15.next=newNode
(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;
head = nodeInsert;// head指针 重新指向新表头
return head;
}
// 非表头插入
Node pNode = head;
int count = 1;
//这里position被上面的size被限制住了,不用考虑pNode=null
while (count < position - 1) { // 利用count 来找到 目标结点的前一个位置
pNode = pNode.next;
count++;
}
nodeInsert.next = pNode.next;//此时pNode在目标结点的前一个位置
pNode.next = nodeInsert;
return head;
}
3.链表删除元素
(1)删除表头结点
删除表头元素:一般只要执行head=head.next。将head向前移动一次之后,原来的结点不可达,会被JVM回收掉。
(2)删除最后一个结点
找到要删除的结点的前驱结点,这里同样要在提前一个位置判断,
例如 要删除node40,其前驱结点为node7。遍历的时候需要判断cur.next是否为node40,如果是,则只要执行cur.next=null
(3)删除中间结点
删除中间结点时,也会要用cur.next来比较,找到要删除的结点的前驱结点的位置后,将cur.next指针的值更新为cur.next.next
删除代码实现:
/**
* 删除节点
* @param head 链表头节点
* @param position 删除节点位置,取值从1开始
* @return 删除后的链表头节点
*/
public static Node deleteNode(Node head, int position) {
if (head == null) {
return null;
}
int size = getListLength(head);
if (position > size || position <1) {
System.out.println("输入的参数有误");
return head;
}
if (position == 1) {//删除表头结点
//curNode就是链表的新head
return head.next;
} else {
Node cur = head;
int count = 1;
while (count < position - 1) {//找到 目标结点的前一个位置
cur = cur.next;
count++;
}
cur.next=cur.next.next
}
return head;
}