(LeetCode 203)Remove Linked List Elements

时间:2023-03-09 03:35:33
(LeetCode 203)Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,  val = 6
Return: 1 --> 2 --> 3 --> 4 –> 5

题目要求:

删除链表中包含val的元素结点

解题思路:

重点在于找到第一个非val的头结点,然后遍历链表,依次删除值为val的结点,最后返回头结点

方法:

1、常规方法:

找到第一个非val的头结点,如果头结点非NULL,遍历链表,依次删除值为val的结点,最后返回头结点。

2、递归方法:

代码:

/**
* 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) {
while(head!=NULL && head->val==val)
head=head->next;
if(head==NULL)
return head;
// At least one node that does not contain val
ListNode* cur;
cur=head;
while(cur->next!=NULL){
if(cur->next->val==val)
cur->next=cur->next->next;
else
cur=cur->next;
}
return 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 && head->val==val)
head=removeElements(head->next,val);
if(head && head->next)
head->next=removeElements(head->next,val);
return head;
}
};