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