leetcode系列(15)移除链表中的指定元素
来源:互联网 发布:ubuntu jdk安装 编辑:程序博客网 时间:2024/05/21 12:44
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. head为空,2. head->val == val,直接上代码吧:
C++ 递归
/** * 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 == nullptr) { return nullptr; } if (head->val == val) { auto ptr = head->next; delete head; head = removeElements(ptr, val); } else { head->next = removeElements(head->next, val); } return head; }};
C 非递归
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode* ptr = head; while (head != NULL && head->val == val) { struct ListNode* ptr = head->next; free(head); head = ptr; } if (head == NULL) { return head; } struct ListNode* pre = head; struct ListNode* cur = head->next; while (cur != NULL) { if (cur->val == val) { pre->next = cur->next; free(cur); } else { pre = cur; } cur = pre->next; } return head;}
Python 非递归
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # @param {ListNode} head # @param {integer} val # @return {ListNode} def removeElements(self, head, val): while head and head.val == val: head = head.next if not head: return None pre = head cur = head.next while cur: if cur.val == val: pre.next = cur.next else: pre = cur cur = cur.next return head
0 0
- leetcode系列(15)移除链表中的指定元素
- Leetcode 27 Remove Element(移除数组中的指定元素)
- leetcode之移除指定元素(PHP)
- leetcode之移除指定元素(PHP)
- 移除数组中的指定元素
- 算法---移除数组中的指定元素(简单)
- 项目常用功能模块(3)-移除数组中的指定元素
- js 移除指定元素
- JQuery移除指定元素
- LeetCode 203 Remove Linked List Elements(移除链表元素)(Linked List)(*)
- 2、(lodash_gcy)移除数组指定元素—remove
- js指定移除数组里面元素
- 移除数组中的元素
- 移除数组中的元素
- 移除数组中的元素
- java算法之简单的移除数组中的指定元素Remove Element
- LeetCode 27 Remove Element(移除元素)
- 安卓谷歌电子市场学习笔记系列——怎么移除集合中的元素(迭代器的使用)
- hihoCoder 1014 Trie树 (Trie)
- ConcurrentModificationException异常总结-多线程方式
- Maven提高篇系列之——使用Profile
- Struts2之数据标签(一)
- Motion Segmentation by Velocity Clustering with Estimationof Subspace Dimension阅读报告
- leetcode系列(15)移除链表中的指定元素
- EFM8单片机与I2C外设通信
- 配置文件读取properties(一)
- 操作系统——IO缓存技术
- sdut1730数字三角形问题(dp入门题)
- shell脚本学习知识点(一)
- 2015-7-12
- IOS 两个ViewController 之间传值
- eclipse使用技巧总结