Leetcode-移除链表元素

C  设置哨兵节点,常规解法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

//prev->next= curr->next
/*
设置一个哨兵节点,作为第一个节点的前驱节点,然后循环判断即可,不过最后要记得释放哨兵节点,否则会
超出时间限制的
*/
struct ListNode* removeElements(struct ListNode* head, int val){
    if(!head){
        return NULL;
    }
    //设置一个节点,是第一个节点的前驱节点
   struct ListNode *first = malloc(sizeof(struct ListNode));
   first->next = head;
   struct ListNode *prev=first,*curr=head;
   while(curr!=NULL){
       if(curr->val == val){
           prev->next = curr->next;
       }else{
           prev = curr;
       }
       curr = curr->next;
   }
   head = first->next;
   free(first);//释放内存,要不然会超出时间限制
   return head;

递归方法

链表 一般都是具有天然的递归性

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

/*
递归 来判断 链表
*/
struct ListNode* removeElements(struct ListNode* head, int val){
    if(!head){
        return NULL;
    }
    //直到到达链表尾部才开始删除重复元素
   head->next = removeElements(head->next,val);

   return head->val == val?head->next:head;
}

C++ 迭代方法 

直接循环判断,最后再来判断head节点是否等于val值

/**
 * 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){
            return NULL;
        }
      struct ListNode *p =head,*q;
      while(p->next){
          if(p->next->val==val){
              p->next=p->next->next;
          }else{
              p=p->next;
          }
      }
      return head->val == val?head->next:head;
    }
};

python 递归方法

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

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        if not head:return
        head.next = self.removeElements(head.next,val)
        return head.next if head.val == val else head

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值