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

(LeetCode 203)Remove Linked List Elements

时间:2015-04-28 01:48:33      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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的元素结点

解题思路:

重点在于找到第一个非val的头结点,然后遍历链表,依次删除值为val的结点,最后返回头结点

方法:

1、常规方法:

找到第一个非val的头结点,如果头结点非NULL,遍历链表,依次删除值为val的结点,最后返回头结点。

2、递归方法:

代码:

/**
 * 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) {
        while(head!=NULL && head->val==val)
            head=head->next;
        if(head==NULL)
            return head;
        // At least one node that does not contain val
        ListNode* cur;
        cur=head;
        while(cur->next!=NULL){
            if(cur->next->val==val)
                cur->next=cur->next->next;
            else
                cur=cur->next;
        }
        return head;
    }
};
/**
 * 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 && head->val==val) 
            head=removeElements(head->next,val);
        if(head && head->next) 
            head->next=removeElements(head->next,val);
        return head;
    }
};

(LeetCode 203)Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/AndyJee/p/4461854.html

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