zoukankan      html  css  js  c++  java
  • 一种怪异的节点删除方式

    【说明】:

      本文是左程云老师所著的《程序员面试代码指南》第二章中“一种怪异的节点删除方式”这一题目的C++复现。

      本文只包含问题描述、C++代码的实现以及简单的思路,不包含解析说明,具体的问题解析请参考原书。

      感谢左程云老师的支持。

    【题目】:

      链表节点值类型为 int 型,给定一个链表中的节点 node,但不给定整个链表的头节点。如何在链表中删除 node?请实现这个函数,并分析这么做会出现那些问题。

      要求:额外的空间复杂读为 O(1)。

     【思路】:

      解法:利用下一个节点替换待删除节点

      缺点:无法删除最后一个节点

    【编译环境】:

      CentOS6.7(x86_64)

      gcc 4.4.7

     【实现】:

      实现及测试代码:

     1 /*
     2  *文件名:list_remove.cpp
     3  *作者:
     4  *摘要:删除无head 节点的链表的指定节点node
     5  */
     6 
     7 #include <iostream>
     8 #include <stdexcept>
     9 
    10 using namespace std;
    11 
    12 class Node
    13 {
    14 public:
    15     Node(int data)
    16     {
    17         value = data;
    18         next = NULL;
    19     }
    20 public:
    21     int value;
    22     Node *next;
    23 };
    24 
    25 void removeNodeWired(Node *node)
    26 {
    27     if(NULL == node)
    28         return ;
    29     Node *next = node->next;
    30     if(NULL == next)
    31         throw runtime_error("Can not remove last node!");
    32     node->value = next->value;
    33     node->next = next->next;
    34     delete next;
    35 }
    36 
    37 void printList(Node *head)
    38 {
    39     while(NULL != head)
    40     {
    41         cout << head->value << " ";
    42         head = head->next;
    43     }
    44     cout << endl;
    45 }
    46 
    47 int main()
    48 {
    49     Node *head = NULL;
    50     Node *ptr = NULL;
    51     
    52     for(int i =8;i>0;i--)//构造链表
    53     {
    54         if(NULL == head)
    55         {    
    56             head = new Node(i);
    57             ptr = head;
    58             continue;
    59         }
    60         ptr->next = new Node(i);
    61         ptr = ptr->next;    
    62     }
    63     cout << "Before deleted:" << endl;
    64     printList(head);
    65     cout << "After deleted:" << endl;
    66     removeNodeWired(head->next->next);
    67     printList(head);
    68     return 0;
    69 }
    View Code

    注:

      转载请注明出处;

      转载请注明源思路来自于左程云老师的《程序员代码面试指南》。

  • 相关阅读:
    oracle 12C linux centos7.5 安装 12C
    FizzBuzz
    批量判断能否telnet登录
    统计所有机器的挂载情况
    ffmpeg windows vs library 下载地址
    需求文档测试
    接口测试分析
    chrome网页截图
    不要为了测试写一个新系统
    C# 判断是否为数字
  • 原文地址:https://www.cnblogs.com/PrimeLife/p/5445095.html
Copyright © 2011-2022 走看看