单链表删除节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
练习链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
代码:
递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteNode(struct ListNode* head, int val)
{
if(!head) return head;
if(head->val== val) return head->next;
head->next = deleteNode(head->next,val);
return head;
}
或者
public ListNode deleteNode(ListNode head, int val) {
if (head == null)
return head;
if (head.val == val)
return head.next;
head.next = deleteNode(head.next, val);
return head;
}
作者:sdwwld
链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/solution/shuang-zhi-zhen-he-di-gui-liang-chong-fang-shi-jie/
来源:力扣(LeetCode)
解释:
无论是 if (head == null)还是 if(!head) return head; 都表示递归的终止条件,当指针指向空地址时,直接返回head(空链表)
if (head.val == val)
return head.next;
通过指针访问地址的节点的值与val相等,直接返回下一个节点的值(即完成了删除的操作)
head.next = deleteNode(head.next, val);
return head;
第一个head.next 头结点的下一个
所以最后的return head 是完成递归后,头结点head
以此为例:
指针指向的操作
一定要先赋值,再调整指针指向
1.创建一个指针,存放删除节点node 的下一个节点的地址
2.将node后一个节点的值赋值给node
3.删除节点node的下一个