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:\n\t"); 36 while( pT != NULL ) 37 { 38 printf("%d ", pT->data); 39 pT = pT->next; 40 } 41 42 printf("\n"); 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\n"); 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 }
每天一个小算法(4)----在O(1)时间删除指定结点,布布扣,bubuko.com
原文:http://www.cnblogs.com/yrpen/p/3785804.html