您的位置:首页 > 其它

[leetcode] 203. Remove Linked List Elements 解题报告

2016-01-07 13:53 330 查看
题目链接: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

思路:需要注意的是头需要删除,因此可以先判断链表头指针不为指定的数,然后再判断下一个是否删除。这样写代码不是很整洁,一种比较好的方式是建立一个虚拟头指针指向首部,然后操作完再删掉。
代码如下:

/**
* 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) return NULL;
ListNode* pHead = new ListNode(0);//建立一个虚头节点
pHead->next = head;
ListNode* p = pHead;
while(p->next)
{
ListNode* q = p->next;
if(q->val == val)
{
p->next = q->next;
delete q;
}
else
p = p->next;
}
head = pHead->next;
delete pHead;
return head;
}
};
参考:http://blog.csdn.net/kangrydotnet/article/details/45220391
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: