[LeetCode203]Remove Linked List Elements

题目:

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) {
ListNode *preHead = new ListNode();
preHead->next = head;
ListNode *cur = head, *pre = preHead;
while(cur)
{
if(cur->val == val)
pre->next = cur->next;
else
pre = pre->next;
cur = cur->next;
}
return preHead->next;
}
};
上一篇:mysql数据库之索引和分析索引


下一篇:WEBBASE篇: 第十一篇, JavaScript知识6