zoukankan      html  css  js  c++  java
  • 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的节点,可以先找到这个节点,然后用上面的方法删除它。可以不用找它前一个节点了。

  • 相关阅读:
    python学习---字符编码
    python学习--变量
    python学习--pycharm编辑器及优化设置
    python学习--第一个python程序helloworld
    python安装
    python学习---python2与python3的区别
    win7下weblogic安装与部署项目调试记录
    ubuntu获得root用户权限,使用xshell连接!
    linux命令
    nginx + tomcat 集群记录
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5843551.html
Copyright © 2011-2022 走看看