Description:
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
思路:本题删除链表中的指定节点。比较简单,首先考虑头结点是否是指定节点,若不是则向后遍历,遇到指定节点直接跳过即可。
C++ 代码
/** * 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 NULL; while(head->val == val) { head = head->next; if (!head) return NULL; } ListNode* res = head; while(head->next) { if(head->next->val == val) head->next = head->next->next; else head = head->next; } return res; } };
运行时间:28ms
运行内存:11M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于