在O(1)时间删除链表节点
来源:互联网 发布:乐乎pt被关了 编辑:程序博客网 时间:2024/06/05 05:54
思路:
时间复杂度要求为O(1),已知要删除的节点,可以找到该节点的下一个节点,把下一个节点的相关信息复制到要删除的节点上,删除下一个节点,可以达到题目要求。
注意:删除尾节点时需要遍历一遍,删除头结点时,需要把头结点移到下一个节点。
#include<stdio.h>#include<stdlib.h>#include<assert.h>struct Listnode{int _value;Listnode* _next;};void Init(Listnode*& head){Listnode* cur =head;if(cur==NULL){cur=(Listnode*)malloc(sizeof(Listnode));cur->_next=NULL;cur->_value=0;}head=cur;}void push(Listnode*& head,int value){Listnode* cur =head;while(cur->_next){cur=cur->_next;}Listnode* tmp=NULL;tmp=(Listnode*)malloc(sizeof(Listnode));tmp->_next=NULL;tmp->_value=value;cur->_next=tmp;}void pop(Listnode* head){Listnode* cur=head;Listnode* prev=NULL;while(cur->_next!=NULL){prev=cur;cur=cur->_next;}prev->_next=NULL;free(cur);cur=NULL;}void print(Listnode* head){Listnode* cur=head;while(cur){printf("%d\n",cur->_value);cur=cur->_next;}}Listnode* Find(Listnode* head,int value){assert(head);Listnode* cur=head; while(cur){if(cur->_value==value){return cur;}else{cur=cur->_next;}}}void DeleteNode(Listnode* &head,Listnode* pToBeDeleted){Listnode* cur=head;if(cur==NULL){return;}if(pToBeDeleted==head){head=cur->_next;free(cur);cur=NULL;return;}Listnode* last=pToBeDeleted->_next;if(last!=NULL){pToBeDeleted->_value=last->_value;pToBeDeleted->_next=last->_next;free(last);last=NULL;}else //删除的是尾节点{Listnode* prev=NULL;while(cur->_next!=NULL){prev=cur;cur=cur->_next;}prev->_next=NULL;free(cur);cur=NULL;}}void test(){Listnode* head=NULL;Init(head); push(head,1);push(head,2);push(head,3);/*pop(head);*/print(head);Listnode* tmp=Find(head,1);DeleteNode(head,head);print(head);}int main(){test();system("pause");return 0;}
结果:
本文出自 “liveyoung” 博客,转载请与作者联系!
0 0
- 在O(1)时间删除链表节点
- 在O(1)时间复杂度删除链表节点
- 在O(1)时间删除链表节点
- 在O(1)时间删除链表节点
- 在O(1)时间删除链表的节点
- 在O(1时间删除链表节点
- 在O(1)时间删除链表节点
- 剑指offer13-在O(1)时间删除链表节点
- 在O(1)时间删除链表节点
- 题目:在O(1)时间复杂度删除链表节点
- LintCode-在O(1)时间复杂度删除链表节点
- lintcode 在O(1)时间复杂度删除链表节点
- 在O(1)时间复杂度删除链表节点
- 在O(1)时间复杂度删除链表节点
- 在O(1)时间删除链表节点
- LintCode:在O(1)时间复杂度删除链表节点
- LintCode_372_在O(1)时间复杂度删除链表节点
- 在O(1)时间复杂度删除链表节点
- 三角形类雏形2
- SIGCHLD 信号
- sig_atomic_t类型与volatile限定符
- 回调函数与函数指针
- 可重入函数与线程安全
- 在O(1)时间删除链表节点
- 调整数组顺序使奇数位于偶数前面
- 二进制中1的个数
- 数值的整数次方
- 斐波那契数列的第n项。
- 从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数
- 求旋转数组的最小值
- 打印1到最大的n位数。
- 协议分析复习