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

leetcode 203. 移除链表元素(Remove Linked List Elements)

时间:2019-03-20 17:28:46      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:==   struct   div   nod   elements   pre   element   delete   lis   

题目描述:

删除链表中等于给定值 val 的所有节点。

示例:

    输入: 1->2->6->3->4->5->6, val = 6
    输出: 1->2->3->4->5

解法:

/**
 * 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) {
        ListNode* cur = NULL;
        while(head && head->val == val){
            cur = head;
            head = head->next;
            delete cur;
        }
        
        cur = head;
        ListNode* nxt = NULL;
        if(head){
            nxt = head->next;
        }
        while(nxt){
            // cout<<nxt->val<<endl;
            if(nxt->val == val){
                cur->next = nxt->next;
                delete nxt;
                nxt = cur->next;
            }else{
                cur = nxt;
                nxt = nxt->next;
            }
        }
        return head;
    }
};

leetcode 203. 移除链表元素(Remove Linked List Elements)

标签:==   struct   div   nod   elements   pre   element   delete   lis   

原文地址:https://www.cnblogs.com/zhanzq/p/10566059.html

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