Easy-题目51:203. 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
题目大意:
删除单链表中指定节点。
题目分析:
用两个指针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%.

你可能感兴趣的:(Easy-题目51:203. Remove Linked List Elements)