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

[LeetCode]203.Remove Linked List Elements

时间:2015-05-02 09:37:29      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:leetcode   经典面试题   链表   

题目

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

思路

链表节点的删除操作。

代码

/*---------------------------------------
*   日期:2015-05-01
*   作者:SJF0115
*   题目: 203.Remove Linked List Elements
*   网址:https://leetcode.com/problems/remove-linked-list-elements/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(nullptr){}
};

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head == nullptr){
            return nullptr;
        }//if
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* cur = head;
        ListNode* tmp;
        while(cur){
            if(cur->val == val){
                tmp = cur;
                pre->next = cur->next;
                delete tmp;
                cur = pre->next;
            }//if
            else{
                pre = cur;
                cur = cur->next;
            }//else
        }//while
        return dummy->next;
    }
};

int main() {
    Solution solution;
    ListNode* head = new ListNode(1);
    ListNode* node1 = new ListNode(5);
    ListNode* node2 = new ListNode(2);
    ListNode* node3 = new ListNode(1);
    ListNode* node4 = new ListNode(4);
    ListNode* node5 = new ListNode(1);
    head->next = node1;
    node1->next = node2;
    node2->next = node3;
    node3->next = node4;
    node4->next = node5;

    head = solution.removeElements(head,6);
    while(head){
        cout<<head->val<<endl;
        head = head->next;
    }//while
}

运行时间
技术分享

[LeetCode]203.Remove Linked List Elements

标签:leetcode   经典面试题   链表   

原文地址:http://blog.csdn.net/sunnyyoona/article/details/45437427

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