Remove Linked List Elements
来源:互联网 发布:如何查看h3c端口 编辑:程序博客网 时间:2024/06/03 17:26
Description:
Remove all elements from a linked list of integers that have value val.
问题描述:
删除链表中所有某特定值的元素。给定链表的头结点和指定的值,编写函数返回处理过的链表的头结点。
Ex:
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
解法一:
思路:
首先进行特殊条件检查,排查空链表的情况。另外如果头结点为待删除的值,直接删掉。先将头结点赋值给临时结点,再进行循环,找到该值就跳过该结点,否则继续遍历结点查找。
code:
/** * 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) { if (head == null) { return null; } ListNode temp = head; while (temp.next != null) { if (temp.next.val == val) { temp.next = temp.next.next; } else { temp = temp.next; } } if (head.val == val) { head = head.next; } return head; }}
0 0
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- MFC定时器
- 图割论文阅读笔记:Min-cut/Max-flow
- 写登录接口,需注意的问题
- ubuntu开机只有界面,没有菜单栏和任务栏
- matlab 编程入门(M文件函数)
- Remove Linked List Elements
- C#调用地图js接口的问题
- 8 泛型编程
- 算法 汽车加油问题
- 解不等式之调和级数不等式
- 网络配置过程分析(linux网络协议栈笔记)
- 全国教师管理信息系统填报 照片处理,使用 imagemagick
- retrolambda在Android studio中的使用
- 8.1 为什么要泛型编程