[leetcode] 203. Remove Linked List Elements
2015-12-01 19:46
260 查看
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
这道题比较简单,删除链表中值是指定值的节点,题目难度为easy。
处理起来比较简单,所以这里不推荐递归的做法,就不列出递归的代码了。唯一需要注意的是链表头节点需要删除时head的赋值。具体代码:
Example
Given:
1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,
val = 6
Return:
1 --> 2 --> 3 --> 4 --> 5
这道题比较简单,删除链表中值是指定值的节点,题目难度为easy。
处理起来比较简单,所以这里不推荐递归的做法,就不列出递归的代码了。唯一需要注意的是链表头节点需要删除时head的赋值。具体代码:
class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* cur = head; ListNode* pre = NULL; while(cur) { if(cur->val == val) { if(cur == head) head = head->next; if(pre) pre->next = cur->next; } else { pre = cur; } cur = cur->next; } return head; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解