zoukankan      html  css  js  c++  java
  • 每天一个小算法(4)----在O(1)时间删除指定结点

    O(1)时间内删除结点的思路只能是复制该结点下一个结点的数据,然后删除该结点的下一个结点,来等效删除此结点。

    需要注意的地方是删除头结点和尾结点的处理。

     1 #include <stdio.h>
     2 #include <time.h>
     3 #include <stdlib.h>
     4 typedef struct Node
     5 {
     6     int data;
     7     Node* next;
     8 }Node, *List;
     9 
    10 List createList(int num) //随机生成数字,构造链表
    11 {
    12     List aList = (List)malloc(sizeof(Node));
    13     aList->next = NULL;
    14     aList->data = 0;
    15     Node* qT = aList;
    16 
    17      // srand((int)time(0));
    18      for ( int i=0; i< num; ++i)
    19      {
    20          Node* pTN = (Node*)malloc(sizeof(Node));
    21          pTN->data = rand()%100;
    22          pTN->next = NULL;
    23          qT->next = pTN;
    24          qT = pTN;
    25      }
    26      return aList;
    27 }
    28 
    29 void printList(List aList)    //打印链表
    30 {
    31     if ( aList == NULL || aList->next == NULL )
    32         return;
    33 
    34     Node* pT = aList->next;
    35     printf("element of list:
    	");
    36     while( pT != NULL )
    37     {
    38         printf("%d ", pT->data);
    39         pT = pT->next;
    40     }
    41 
    42     printf("
    ");
    43 }
    44 
    45 void deleteList(List aList)    //删除链表
    46 {}
    47 
    48 
    49 //删除结点主算法
    50 void deleteNode(List aList, Node* pNode)
    51 {
    52     if ( aList == NULL || pNode == NULL )
    53         return;
    54 
    55     if ( aList == pNode )
    56     {
    57         printf("refuse to delete head node
    ");
    58         return;
    59     }
    60 
    61     if ( pNode->next == NULL )
    62     {
    63         Node* pT = aList->next;
    64         while ( pT->next != NULL )
    65         {
    66             pT = pT->next;
    67         }
    68 
    69         delete pNode;
    70         pT->next == NULL;
    71     }
    72 
    73     Node* pN = pNode->next;
    74     pNode->data = pNode->next->data;
    75     pNode->next = pNode->next->next;
    76 
    77     delete pN;
    78 }
    79 
    80 int main(int argc, char const *argv[])
    81 {
    82      srand((int)time(0));
    83     List aList = createList(5);
    84     printList(aList);
    85     deleteNode(aList,aList->next->next);
    86     printList(aList);
    87     deleteList(aList);
    88     
    89     return 0;
    90 }
  • 相关阅读:
    核新同花顺数据结构
    python发送各类邮件的主要方法
    Tesseract-OCR引擎 入门
    ruby函数回调的实现方法
    软件单元测试之我见
    cocos cteator中tiled模式 用图集容易出线
    入坑CCC遇到的一些坑啊
    关于委托的理解
    火狐浏览器的三个坑
    抗锯齿的BUG
  • 原文地址:https://www.cnblogs.com/yrpen/p/3785804.html
Copyright © 2011-2022 走看看