LeetCode:Remove Linked List Elements
来源:互联网 发布:悟空源码 编辑:程序博客网 时间:2024/06/05 05:22
问题描述:
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
简单说就是去掉链表中指定值的算法,但是要注意,这样的值也许不止一个!
思路:1、先判断头节点以及头节点的后续节点是否是指定值,如果是,删除节点;
2、然后再判断后续节点是否是指定值,如果是,删除节点,如果不是,一次遍历链表,直到最后一个节点。
3、考虑所有情况。
代码实现如下:
<pre name="code" class="cpp">/** * 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 *pointor = head;ListNode *result = head;while(pointor && pointor -> val == val){ListNode *temp = pointor; pointor = pointor -> next; delete temp; }result = pointor;while(pointor){if(pointor -> next && pointor -> next -> val == val){ListNode *temp = pointor -> next;pointor -> next = pointor -> next -> next;delete temp;continue;}pointor = pointor -> next;}return result; }};
1 0
- [LeetCode] Remove Linked List Elements
- [LeetCode]Remove Linked List Elements
- Leetcode--Remove Linked List Elements
- [LeetCode]Remove Linked List Elements
- leetcode Remove Linked List Elements
- [LeetCode] Remove Linked List Elements
- [leetcode]Remove Linked List Elements
- leetcode--Remove Linked List Elements
- [LeetCode] Remove Linked List Elements
- 【leetcode】Remove Linked List Elements
- LeetCode:Remove Linked List Elements
- [leetcode]Remove Linked List Elements
- Remove Linked List Elements [leetcode]
- LeetCode: Remove Linked List Elements
- LeetCode Remove Linked List Elements
- [Leetcode]Remove Linked List Elements
- LeetCode Remove Linked List Elements
- Remove Linked List Elements -- leetcode
- LinuxCNC+EtherCAT(6)之LinuxCNC使用,翻译
- CentOS 6.5 (CentOS 7)安装过程记录
- 开发:日期格式的处理(日期终结者)
- Intent中的四个重要属性——Action、Data、Category、Extras
- 测试用例的编写
- LeetCode:Remove Linked List Elements
- lintcode-链表插入排序
- iOS开发11-iOS 数据持久化(简单、复杂对象的读写)
- C语言传参不支持引用
- 百度面试题2012
- uva 11594 划分回文串
- leetcode之Binary Tree Inorder Traversal
- 关于S3C2440从NAND Flash启动的问题
- 黑马程序员——Java基础语法 之面向对象(概念,特征,this,static关键字,代码块)