Remove Linked List Elements
程序员文章站
2022-04-18 19:26:56
...
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
这题比较简单,有一点要记住的是,如果删除当前节点,那么当前节点就不需要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) {
if(head == NULL)return NULL;
ListNode *p = new ListNode(0), *q;
p->next = head;
q = p;
while(p && p->next)
{
if(p->next && p->next->val == val)
{
p->next = p->next->next;
}
else
p = p->next;
}
return q->next;
}
};
推荐阅读
-
Java list.remove( )方法需要注意的地方
-
Python 删除List元素的三种方法remove、pop、del
-
【LeetCode OJ 328】Odd Even Linked List
-
数据结构与算法 —— 链表linked list(04)
-
PTA 02-线性结构3 Reversing Linked List (25 分)
-
PAT-A-1052 Linked List Sorting
-
leetcode 328. Odd Even Linked List
-
leetcode 328. Odd Even Linked List
-
328. Odd Even Linked List
-
328. Odd Even Linked List。