您的位置:首页 > 编程语言 > C语言/C++

Leetcode 203. Remove Linked List Elements (Easy) (cpp)

2016-07-12 12:49 441 查看
Leetcode 203. Remove Linked List Elements (Easy) (cpp)

Tag: Linked List

Difficulty: Easy

/*

203. Remove Linked List Elements (Easy)

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

*/
/**
* 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 == NULL) {
return head;
}
ListNode dummy(-1);
ListNode *prev = &dummy;
do {
if (head -> val == val) {
head = head -> next;
} else {
prev -> next = new ListNode(head -> val);
prev = prev -> next;
head = head -> next;
}
}while (head != NULL);
return dummy -> next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: