203. Remove Linked List Elements(简单)

203. Remove Linked List Elements(简单)

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

在这里插入图片描述

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1
Output: []

Example 3:

Input: head = [7,7,7,7], val = 7
Output: []

思路:

  1. 添加哑节点来避免需要判断head是否为NULL;然后遍历链表,找到待删节点的前驱节点,和后继节点,将后继节点链接到前驱节点上即可。

  2. C++

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode*  newhead = new ListNode();
        ListNode* p = newhead;
        p->next = head;
        ListNode* prec = p;
        while(p!=nullptr ){
            if(p->val == val){
                prec->next = p->next;
                p = prec->next;
            }

            else{
                prec = p;
                p = p->next;
            }
            
        }
        return newhead->next;
        
      	// ListNode* p = new ListNode(0, head);
        // ListNode* newhead = p;
        // while(p->next!=nullptr){
        //     if(p->next->val== val){
        //         ListNode* temp = p->next;
        //         p->next = p->next->next;
        //         delete temp;
        //     }
        //     else{
        //         p = p->next;
        //     }
        // }
        // head = newhead->next;
        // delete newhead;
        // return head;
    }
};

  1. python
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        newhead = ListNode(0,head)
        p = newhead
        prec = p
        while(p!=None):
            if p.val == val:
                prec.next = p.next
                p = prec.next
            else:
                prec = p
                p = p.next
        return newhead.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值