zoukankan      html  css  js  c++  java
  • [剑指offer]Q13:O(1)时间删除链表的结点

    通常我们所说的删除链表的某个结点,是彻底删除该结点的空间。而要这么做就必须知道其前驱结点。这里的想法是,链表中存储的val是同类型的,仅仅要将该结点的val内容删除就能够了。

    那么就能够用该结点的后继结点的值覆盖当前结点,然后删除其后继结点,而对于其后继结点而言,该结点就是前驱。

    这里仅仅须要考虑当前删除的结点是否为last node 就能够了。至于是否是头结点。这样的情况是能够归为同一种情况的。仅仅是參数要稍作改动。

    void delNode(ListNode **head, ListNode **toDel)
    {
    	if(*toDel == NULL || head == NULL || *head == NULL)
    		return;
    	// toDel is the last node
    	if( (*toDel)->next == NULL){
    		// notice: order of delete and assi null
    		delete *toDel;
    		*toDel = NULL;
    		return;
    	}
    	// toDel is not last node
    	else{
    		ListNode *beDel = (*toDel)->next;
    		(*toDel)->val = beDel->val;
    		(*toDel)->next = beDel->next;
    		delete beDel;
    		beDel = NULL;
    	}
    }




  • 相关阅读:
    Python基础-序列化模块
    dubbox
    小型供销系统
    MyBatis与SpringBoot整合案例(一)
    SpringBoot第二节
    SpringBoot第一节
    Dubbo案例SSM整合
    Dubbo生产者和消费者
    Zookeeper实战分布式锁
    Zookeeper Watcher和选举机制
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7098192.html
Copyright © 2011-2022 走看看