在O(1)时间删除链表节点
思路:
时间复杂度要求为O(1),已知要删除的节点,可以找到该节点的下一个节点,把下一个节点的相关信息复制到要删除的节点上,删除下一个节点,可以达到题目要求。
注意:删除尾节点时需要遍历一遍,删除头结点时,需要把头结点移到下一个节点。
#include<stdio.h>#include<stdlib.h>#include<assert.h>structListnode{int_value;Listnode*_next;};voidInit(Listnode*&head){Listnode*cur=head;if(cur==NULL){cur=(Listnode*)malloc(sizeof(Listnode));cur->_next=NULL;cur->_value=0;}head=cur;}voidpush(Listnode*&head,intvalue){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;}voidpop(Listnode*head){Listnode*cur=head;Listnode*prev=NULL;while(cur->_next!=NULL){prev=cur;cur=cur->_next;}prev->_next=NULL;free(cur);cur=NULL;}voidprint(Listnode*head){Listnode*cur=head;while(cur){printf("%d\n",cur->_value);cur=cur->_next;}}Listnode*Find(Listnode*head,intvalue){assert(head);Listnode*cur=head;while(cur){if(cur->_value==value){returncur;}else{cur=cur->_next;}}}voidDeleteNode(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;}}voidtest(){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);}intmain(){test();system("pause");return0;}
结果:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。