每天一个小算法(4)----在O(1)时间删除指定结点
2014-06-13 14:43
330 查看
O(1)时间内删除结点的思路只能是复制该结点下一个结点的数据,然后删除该结点的下一个结点,来等效删除此结点。
需要注意的地方是删除头结点和尾结点的处理。
需要注意的地方是删除头结点和尾结点的处理。
#include <stdio.h> #include <time.h> #include <stdlib.h> typedef struct Node { int data; Node* next; }Node, *List; List createList(int num) //随机生成数字,构造链表 { List aList = (List)malloc(sizeof(Node)); aList->next = NULL; aList->data = 0; Node* qT = aList; // srand((int)time(0)); for ( int i=0; i< num; ++i) { Node* pTN = (Node*)malloc(sizeof(Node)); pTN->data = rand()%100; pTN->next = NULL; qT->next = pTN; qT = pTN; } return aList; } void printList(List aList) //打印链表 { if ( aList == NULL || aList->next == NULL ) return; Node* pT = aList->next; printf("element of list:\n\t"); while( pT != NULL ) { printf("%d ", pT->data); pT = pT->next; } printf("\n"); } void deleteList(List aList) //删除链表 {} //删除结点主算法 void deleteNode(List aList, Node* pNode) { if ( aList == NULL || pNode == NULL ) return; if ( aList == pNode ) { printf("refuse to delete head node\n"); return; } if ( pNode->next == NULL ) { Node* pT = aList->next; while ( pT->next != NULL ) { pT = pT->next; } delete pNode; pT->next == NULL; } Node* pN = pNode->next; pNode->data = pNode->next->data; pNode->next = pNode->next->next; delete pN; } int main(int argc, char const *argv[]) { srand((int)time(0)); List aList = createList(5); printList(aList); deleteNode(aList,aList->next->next); printList(aList); deleteList(aList); return 0; }
相关文章推荐
- 算法-O(1)时间删除链表的指定结点
- 每天一道算法题2 删除链表结点(时间复杂度为O(1)))
- 算法题14 删除链表结点(时间复杂度为O(1)))
- 微软等数据结构+算法面试100题(31)--在O(1)时间内删除链表结点
- mtk笔试题-----快速删除单链表中一个结点。时间复杂度为o(1)
- 长度为n的顺序表L,编写一个时间复杂度为O(n),空间复杂度为O(1)的算法,该算法删除线性表中所有值为X的元素
- 每天学习一算法系列(18)(n 个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,每次从这个圆圈中删除第m 个数字)
- [原]在O(1)时间内删除链表指定结点
- 给定链表的头指针和一个结点指针,在O(1) 时间删除该结点
- 在O(1)时间删除指定链表结点
- 【每天学点算法题10.15】指定一个字符串,对字符串左旋K位
- 给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点
- 给定链表的头指针和一个结点指针,在O(1) 时间删除该结点
- 每天学习一算法系列(25)(一个台阶总共有n 级,如果一次可以跳1 级,也可以跳2 级,求总共有多少总跳法,并分析算法的时间复杂度。)
- 每天学习一算法系列(6) (输入一个整数和一棵二元树,从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径,打印出和与输入整数相等的所有路径)
- 给定链表的头指针和一个结点指针,在O(1)时间删除该结点
- 在O(1)时间删除链表一个结点
- 给定链表的头指针和一个结点指针,在O(1)时间删除该结点。
- 每天一个小算法(5)----找到链表倒数第K个结点
- 每天一个小程序(2)——带头结点的链表的创建以及插入和删除