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

ps:这一题感觉没什么技巧可言,选取一个头指针,一个当前指针,一个前向指针。简单的链表操作而已,代码如下:

 /**
* 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) {
ListNode * root = head;
ListNode * prev = head;
ListNode * curr = head;
while (curr != NULL){
if (curr->val == val){
if (prev == curr)
root = prev = curr = curr->next;
else{
curr = curr->next;
prev->next = curr;
}
}else{
prev = curr;
curr = curr->next;
}
}
return root;
}
};

java版本如下所示:

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val){
ListNode helper = head;
head = head.next;
helper.next = null;
}
if(head == null)
return head;
ListNode p1 = head;
while(p1.next != null){
if(p1.next.val == val){
p1.next = p1.next.next;
}else
p1 = p1.next;
}
return head;
}
}

最新文章

  1. 札记:Java异常处理
  2. ES6深入学习记录(一)class方法相关
  3. winform公共标签和常用属性
  4. *** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory
  5. unity3D技术之事件函数的执行顺序[转]
  6. bzoj1565
  7. html_table标签和from表单标签小试手
  8. 发布项目到 Linux 上运行 Core 项目
  9. UVA 12230 - Crossing Rivers(概率)
  10. 【Leetcode】Remove Duplicates from Sorted List in JAVA
  11. Markdown速查手册
  12. Python玩转硬件:TPYBoard-Micropython开发板大盘点
  13. obj-c编程01[扩展学习01]:对象消息机制工作原理
  14. Java开发岗面试知识点解析
  15. 测者的性能测试手册:JVM的监控利器
  16. RocketMQ_问题_启动控制台console报错,connect to <null> failed
  17. Failure [INSTALL_CANCELED_BY_USER]
  18. 《Vue 编程房内考》
  19. 设计模式学习--面向对象的5条设计原则之接口隔离原则--ISP
  20. UVALive-4452 The Ministers' Major Mess (2-SAT)

热门文章

  1. python web框架 Django的APP以及目录介绍 django 1.11版本
  2. 011-JDK可视化监控工具-Jstat
  3. android studio 中类似VS的代码折叠功能Region
  4. 【Spring MVC】spring mvc中相同的url请求返回不同的结果
  5. git命令集合
  6. 使用pycharm操作django
  7. 表单向controller传值如果没填controller取到的是null
  8. 高通平台下安卓opencl小例子
  9. menubar下面的选项不可以输入中文
  10. UML学习-1 UML 简介