• Leetcode 237. Delete Node in a Linked List


    Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

    Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4after calling your function.

    题目大意:

    写一个函数删除单链表中的一个节点(除了尾节点),只给出要删除的那个节点。

    分析:一开始没看懂题目意思。。。以为给的是链表头结点。然后我就打算找到这个节点的前一个节点q,然后q ->next = q -> next -> next;这个是删除链表中一个节点的一种办法。

    这里的话可以将这个节点的下一个节点的值赋给这个节点,这个节点的指针指向下下个节点。就实现了删除这个节点(实际上是下一个节点的值覆盖了原来节点的值).

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     struct ListNode *next;
     6  * };
     7  */
     8 void deleteNode(struct ListNode* node) {
     9      if(node == NULL)
    10             return;
    11      node -> val = node -> next -> val;
    12      node -> next = node -> next -> next;
    13 }

    扩展:要删除某个单链表的一个值为val的节点,可以先找到这个节点,然后用上面的方法删除它。可以不用找它前一个节点了。

  • 相关阅读:
    conio
    create file in Linux
    单向链表
    面向对象(Object Oriented,OO)
    LLVM每日谈之五 LLVM文档介绍
    Team Geek 阅读笔记之 第三章 Every Boat Needs a Captain
    重温堆和拷贝构造函数
    LLVM每日谈之六 LLVM的源码结构
    LLVM每日谈之七 Clang
    LLVM每日谈之三 如何创建一个LLVM工程
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5843551.html
Copyright © 2020-2023  润新知