码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Linked List Elements

时间:2016-03-02 23:24:26      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

1、问题描述:

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

2、解决思路:

1)定义两个新节点,头结点赋值给p,头结点的下一个节点赋值给q;

2)当q非空时循环,判断q节点的数据元素是否等于val,

                            if (相等){p->next=q->next; delete q; q=p-next;} 

                           else {p=p->next; q=q->next;}

3)判断头节点元素是否等于val,if(相等){p=head;head=head->next;delete p;} 

4) return head;

3、代码描述:

/**
 * 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 *p,*q;
        p=head;
        q=p->next;
        
        while(q)
        {   
            if(q->val==val)
            {
                p->next=q->next;
                delete q;
                q=p->next;
            }
            else 
            {
                p=p->next;
                q=q->next;
            }
       }
       if(head->val==val)
       {
           p=head;
           head=head->next;
           delete p;
       }
       return head;
    } }; 

Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/baiheniao/p/5236617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!