删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
思路:
递归,首先还是要找终止条件。接下来思路递归需要返回什么,因为处理head->next,head->next后已经是不存在val的链表,所以返回时候需要判断head->val是不是等于val,若相等则返回head->next,否则返回head。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==NULL){
return NULL;
}
head->next=removeElements(head->next,val);
return head->val==val?head->next:head;
}
};
迭代,定义哑结点,工作指针。判断cur->next是否为空,遍历整个链表。如果节点值等于val,cur->next=cur->next->next。否则继续遍历cur=cur->next。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy=new ListNode(0);
dummy->next=head;
ListNode* cur=dummy;
while(cur->next!=NULL){
if(cur->next->val==val){
cur->next=cur->next->next;
}
else{
cur=cur->next;
}
}
auto res=dummy->next;
delete dummy;
return res;
}
};