PROBLEM:
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
SOLVE:
/**
* 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) return head;
head->next=removeElements(head->next,val);
return head->val==val?head->next:head;
}
};
本文介绍了一种从单链表中移除所有指定值节点的方法,并提供了一个递归实现的示例代码。该算法通过递归将待处理节点的后续节点中的指定值移除,再判断当前节点是否为指定值。
157

被折叠的 条评论
为什么被折叠?



