leetcode笔记:Remove Linked List Elements
来源:互联网 发布:tuxera ntfs for mac 编辑:程序博客网 时间:2024/06/14 02:07
一. 题目描述
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
Credits: Special thanks to @mithmatt for adding this problem and creating all test cases.
二. 题目分析
题目大意是从单链表中移除所有值为val的元素。在循环遍历链表时使用cur记录当前元素。注意多种临界情况,如头结点为NULL的时候。
三. 示例代码
// C++版本ListNode* removeElements(ListNode* head, int val) { ListNode* cur = head; while (true) { if (head == NULL) return NULL; if (cur->val != val) break; cur = cur->next; head = cur; } while (cur->next) { if (cur->next->val == val) { cur->next = cur->next->next; } else { cur = cur->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): pre = ListNode(0) pre.next = head cur = pre while cur and cur.next: if cur.next.val == val: cur.next = cur.next.next else: cur = cur.next return pre.next
四. 小结
以上代码可以AC,但在编写过程中并没有考虑delete节点的问题,这样是不对的,由于时间有限,只能下次再改进了。
1 0
- leetcode笔记--Remove Linked List Elements
- leetcode笔记:Remove Linked List Elements
- LeetCode笔记:203. 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
- [leetcode]Remove Linked List Elements
- Remove Linked List Elements [leetcode]
- LeetCode: Remove Linked List Elements
- LeetCode Remove Linked List Elements
- 浅谈HTTP中Get与Post的区别
- 1011 of search
- Android 中的Intent Action 一览表
- LintCode_373_奇偶分割数组
- POJ 1113 Wall(求凸包周长)
- leetcode笔记:Remove Linked List Elements
- 1012 of search
- HTTP 请求方式: GET和POST的比较 3
- git历史版本修改合并到主分支
- py - understanding zip function
- POJ 2007 Scrambled Polygon(极角排序)
- Navicat for MySql 如何插入新记录
- linux开机启动流程
- POJ 1873 The Fortified Forest(凸包+DFS枚举)