思路:
方法一: 创建一个新链表指向链表,直接遍历链表,如果找到val后将指针直接指向下个节点
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode* dummy=new ListNode(-1);
dummy->next=head;
if(!head) return head;
ListNode* cur=dummy;
while(cur->next)
{
if(cur->next->val==val) cur->next=cur->next->next;
else cur=cur->next;
}
return dummy->next;
}
}
方法二:递归的思想
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
//递归的思想
if(!head) return head;
//要删除头结点
if(head->val==val) return head->next;
head->next=deleteNode(head->next,val);
return head;
}
};
Every step of barefoot running deserves to be recorded