leetcode 203. Remove Linked List Elements

本文介绍了如何使用C++删除单链表中指定值的节点,包括定义链表节点结构,实现删除操作,并通过示例代码展示解决方案。

传送门

203. Remove Linked List Elements

    My Submissions
QuestionEditorial Solution
Total Accepted: 62648 Total Submissions: 217789 Difficulty: Easy

 

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.

 

Subscribe to see which companies asked this question

Hide Tags
  Linked List
Show Similar Problems
 
 
题解:
转自:
 

Submission Details

63 / 63 test cases passed.
Status: 
Accepted
Runtime: 32 ms
 
 
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* removeElements(ListNode* head, int val) {
12         ListNode* dummy = new ListNode(0);  
13         dummy->next = head;  
14         ListNode *p = dummy;  
15         ListNode *q = head;  
16         while(q != NULL) {  
17             if(q->val == val) {  
18                 p->next = q->next;  
19                 free(q);
20             } 
21             else {  
22                 p = p->next;  
23             }  
24             q = q->next;  
25         }  
26         return dummy->next;  
27     }
28 };

 

 

单链表的插入与删除

转载于:https://www.cnblogs.com/njczy2010/p/5477499.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值