标签:
题目描述:(链接)
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 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 if (!head) { 13 return head; 14 } 15 16 ListNode dummy(-1); 17 dummy.next = head; 18 ListNode *prev = &dummy; 19 ListNode *cur = prev->next; 20 while (cur != nullptr) { 21 if (cur->val == val) { 22 ListNode *tmpNode = cur; 23 prev->next = cur->next; 24 cur = prev->next; 25 } else { 26 prev = cur; 27 cur = cur->next; 28 } 29 } 30 31 return dummy.next; 32 } 33 };
[LeetCode]Remove Linked List Elements
标签:
原文地址:http://www.cnblogs.com/skycore/p/4948573.html