Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
这道题属于easy,但我做的也不是很快。
我的做法
/**
* 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;
while(head -> val == val){
if(head->next == NULL) return NULL;
else {
head = head -> next;
if (head == NULL) return NULL;
}
}
ListNode *pre=NULL,*now=head;
while (now!=NULL){
if (now -> val == val){
pre->next = now ->next;
now = pre->next;
}
else {
pre = now;
now = now ->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 == NULL) return NULL;
(*head).next = removeElements((*head).next, val);
return (*head).val == val ? (*head).next: head;
}
};