【题目】剑指 Offer 18. 删除链表的节点& 237. 删除链表中的节点 & 面试题 02.03. 删除中间节点
237. 删除链表中的节点和面试题 02.03. 删除中间节点相同,剑指 Offer 18. 删除链表的节点与前两题区别是给的是头结点,要删除的结点也可能是尾结点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:
题目保证链表中节点的值互不相同
若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
【解题思路1】后继结点的值覆盖掉要删除元素的值再断链,考虑删除的是尾结点的情况
237. 删除链表中的节点只需要直接覆盖即可,因为删除的不会是尾结点
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
相比上面的做法,需要先找到要删除的结点,然后还要判断它是否是尾结点
class Solution {
public ListNode deleteNode(ListNode head, int val) {
ListNode cur = head;
ListNode pre = head;
// 找到结点
while(cur != null){
if(cur.val != val){
pre = cur;
cur = cur.next;
}else{
break;
}
}
// 考虑是尾结点的情况
if(cur.next == null){
pre.next = null;
} else {
// 后继结点的值覆盖掉要删除元素的值,最后再将重复元素断链
cur.val = cur.next.val;
cur.next = cur.next.next;
}
return head;
}
}
时间复杂度:O(N)。
空间复杂度:O(1)。
【解题思路2】只断链不覆盖,考虑删除的是头结点的情况
双指针:加入虚拟头结点dummy来避免删除的是头结点的情况
public ListNode deleteNode(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = head;
ListNode pre = dummy;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
break;
} else {
pre = cur;
cur = cur.next;
}
}
return dummy.next;
}
不加虚拟头结点也可以:
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head.val == val) return head.next;
ListNode pre = head, cur = head.next;
while(cur != null && cur.val != val) {
pre = cur;
cur = cur.next;
}
if(cur != null) pre.next = cur.next;
return head;
}
}
双指针:单独考虑头结点的情况
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head == null) return head;
ListNode cur = head;
if(cur.val == val) return cur.next;
ListNode pre = cur;
while(cur != null) {
if(cur.val == val) {
pre.next = cur.next;
break;
} else {
pre = cur;
cur = cur.next;
}
}
return head;
}
}
单指针:省掉pre的写法:
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null) return head;
if (head.val == val) return head.next;
ListNode cur = head;
while (cur.next != null && cur.next.val != val) {
cur = cur.next;
}
cur.next = cur.next.next;
return head;
}
}
时间复杂度:O(N)。
空间复杂度:O(1)。