示例1
输入:
{2,5,1,9},5
返回值:
{2,1,9}
说明:
给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 2 -> 1 -> 9
示例2
输入:
{2,5,1,9},1
复制
返回值:
{2,5,9}
复制
说明:
给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 2 -> 5 -> 9
解题思路
如何要删除的节点为头节点,要单独处理。否则pre->next = cur -> next;
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param val int整型
* @return ListNode类
*/
struct ListNode* deleteNode(struct ListNode* head, int val ) {
if(!head)return NULL;
//如何要删除的节点为头节点
if(head->val==val) return head->next;
// write code here
struct ListNode* pre = (struct ListNode *)malloc(sizeof(struct ListNode));
pre->val = -1;
pre->next = head;
struct ListNode* cur = head;
while(cur){
if(cur->val==val){
pre->next =cur->next;
cur->next = NULL;
break;
}
pre = pre->next;
cur = cur->next;
}
return head;
}