leetcode系列(15)移除链表中的指定元素

来源:互联网 发布:ubuntu jdk安装 编辑:程序博客网 时间:2024/05/21 12:44

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

这个题目比较简单,用递归方法非常简洁,但是要注意两个情况:1. head为空,2. head->val == val,直接上代码吧:

C++ 递归

/** * 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 == nullptr) {            return nullptr;        }        if (head->val == val) {            auto ptr = head->next;            delete head;            head = removeElements(ptr, val);        } else {            head->next = removeElements(head->next, val);        }        return head;    }};

C 非递归

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* removeElements(struct ListNode* head, int val) {    struct ListNode* ptr = head;    while (head != NULL && head->val == val) {        struct ListNode* ptr = head->next;        free(head);        head = ptr;    }        if (head == NULL) {        return head;    }        struct ListNode* pre = head;    struct ListNode* cur = head->next;    while (cur != NULL) {        if (cur->val == val) {            pre->next = cur->next;            free(cur);        } else {            pre = cur;        }        cur = pre->next;    }    return head;}



Python 非递归

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param {ListNode} head    # @param {integer} val    # @return {ListNode}    def removeElements(self, head, val):        while head and  head.val == val:            head = head.next        if not head:            return None        pre = head        cur = head.next        while cur:            if cur.val == val:                pre.next = cur.next            else:                pre = cur            cur = cur.next        return head                                        


0 0
原创粉丝点击