#452 Remove Linked List Elements

来源:互联网 发布:js拖拽事件绑定数据 编辑:程序博客网 时间:2024/06/05 15:27

题目描述:

Remove all elements from a linked list of integers that have value val.

Example

Given 1->2->3->3->4->5->3, val = 3, you should return the list as1->2->4->5

题目思路:

这题用上dummy head,轻松可解。

Mycode(AC = 27ms):

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    /**     * @param head a ListNode     * @param val an integer     * @return a ListNode     */    ListNode *removeElements(ListNode *head, int val) {        // Write your code here        ListNode *dummy = new ListNode(0);        dummy->next = head;                ListNode *ptr = dummy;        while (ptr->next) {            // if ptr->next is val, then link ptr            // to ptr->next->next, ptr still stays            if (ptr->next->val == val) {                ptr->next = ptr->next->next;            }            else {// ptr goes next                ptr = ptr->next;            }        }                return dummy->next;    }};


0 0
原创粉丝点击