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

[C++]Remove Linked List Elements 删除链表中的元素

2015-08-27 21:23 507 查看
leetcode 原题链接:https://leetcode.com/problems/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
简要分析:该题就是把与给定的val值相同的元素从链表中删除
需要注意的是,删除的点在链表头与表身需要分开处理。

实现代码:

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