leetcode--203--移除链表元素

2020-07-22  本文已影响0人  minningl

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

示例:

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

思路:
1、采用递归的方法进行解决。那就的定义好终止条件,如果head为空,则返回head。否则递归的调用当前函数

Python代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return head
        head.next = self.removeElements(head.next, val)
        if head.val==val:
            return head.next
        else:
            return head
        

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 head;

        head->next = removeElements(head->next, val);
        if(head->val==val){
            return head->next;
        }else{
            return head;
        }
    }
};
上一篇 下一篇

猜你喜欢

热点阅读