Easy-题目51:203. Remove Linked List Elements

转载 2016年05月30日 20:50:40

题目原文:
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
题目大意:
删除单链表中指定节点。
题目分析:
用两个指针p和q(p始终是q前驱节点)并行向后推,若找到q是待删除节点(q->val==val)则删除q,但还没有处理头结点,故看一下head->val与val是否相等。
源码:(language:cpp)

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *p=head;
        if(!p || (!p->next && p->val==val))//p is null or (length of linklist=1 and this unique node is going to be deleted)
            return NULL;
        else {
            ListNode *q=head->next;
            while(q) {
                if(q->val==val) {// the first node is going to be deleted
                    p->next=p->next->next;
                    q=q->next;
                    continue;
                }
                else {
                    p=p->next;
                    q=q->next;
                }
            }
            if(head->val!=val)
                return head;
            else
                return head->next;
        }
    }
};

成绩:
32ms,beats 54.36%,众数36ms,45.72%.

相关文章推荐

Leetcode 203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.Example Given: 1 –> 2 –> 6 –...

Leetcode_203_Remove Linked List Elements

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/45868027 Remove all el...

203. Remove Linked List Elements

描述: Remove all elements from a linked list of integers that have value val.Example Given: 1 –> 2 –...

leetcode 203. Remove Linked List Elements

我觉得在使用链表的时候一般有两种思路:一种是链表的内容可以修改,在原链表上进行处理,后续的操作不需要使用原链表的内容的时候这种思路可以节约空间和时间;另外一种是当我们不能更改链表的内容,后续需要用到的...

Remove Linked List Elements - LeeCode 203

题目描述: Remove all elements from a linked list of integers that have value val. Example Given: 1 ...

<LeetCode OJ> 203. Remove Linked List Elements

203. Remove Linked List Elements My Submissions Question Total Accepted: 45239 Total Submissions...

leetcode题解-203. Remove Linked List Elements

题目:Remove all elements from a linked list of integers that have value val.Example Given: 1 --> 2 -->...

[LeetCode]203 Remove Linked List Elements

原题链接QuestionRemove all elements from a linked list of integers that have value val.Example Given: 1...

LeetCode 203 Remove Linked List Elements(移除链表元素)(Linked List)(*)

翻译从一个链表中移除所有值为val的元素。例如 给定:1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 返回:1 --> 2 --> 3 --> 4 -->...
  • NoMasp
  • NoMasp
  • 2016-01-28 08:58
  • 1710

Remove Linked List Elements

Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 -...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)