题目介绍
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。原题链接
示例 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.
解题思路
该题只要找到结点的值等于输入的值就行,即 currentNode.val == val 就行。这个题目唯一要解决的就一个问题:因为是单向链表,是找不到前面的结点的。所以我们需要一个能够记录当前结点的前一个结点的指针。这样才能将该结点删除的时候不至于让链表断开。
思路一:
直接上代码:
//空节点直接返回
if (head == null){
return null;
}
//要删除的是头节点
if (head.val == val ){
return head.next;
}
ListNode currentNode = head;
ListNode nextNode = head.next;
while (nextNode != null){
if (nextNode.val == val){
currentNode.next = nextNode.next;
}
currentNode = nextNode;
nextNode = nextNode.next;
}
return head;
思路二:
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;
}
}
作者:Krahets
链接:https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/solutions/167212/mian-shi-ti-18-shan-chu-lian-biao-de-jie-dian-sh-2/
来源:力扣(LeetCode)
方法二 和 方法一 都是使用了双指针,方法二更加巧妙的将结点设计在了头节点前面,不需要对头结点进行特殊处理。
总结
链表虽然是一种比较简单的数据结构,但是对指针进行操作的时候一定要谨慎思考,否则会给你的求解带来额外的负担。