C++实现O(1)时间内删除链表结点
/* * 删除链表节点.cpp * * Created on: 2018年4月13日 * Author: soyo */ #include<iostream> using namespace std; struct node { int data; node * next; }; node * create_head(node *p,int v) { p=new node; p->data=v; p->next=NULL; return p; } node * add_list(node*head,int n) { node *p,*p1; p=head; p1=new node; p1->data=n; p1->next=NULL; while(p->next!=NULL) p=p->next; p->next=p1; return head; } void println(node *head) { if(head==NULL) return; while(head!=NULL) { cout<<head->data<<" "; head=head->next; } cout<<endl; } void deletNode(node**head,node*deleteNode) { if(head==NULL||deleteNode==NULL) return; if(deleteNode->next!=NULL) //要删除的结点不是尾结点 { node *nextNode=deleteNode->next; deleteNode->data=nextNode->data; deleteNode->next=nextNode->next; delete nextNode; nextNode=NULL; } else if(*head==deleteNode) //只有一个结点 { delete deleteNode; deleteNode=NULL; *head=NULL; } else { node *p=*head; while(p->next!=deleteNode) //删除的结点为尾结点 { p=p->next; } p->next=NULL; delete deleteNode; deleteNode=NULL; } } int main() { node *p,*head; int data=5; head=create_head(p,data); int a[]={2,4,6,7,8,9}; int c=sizeof(a)/sizeof(int); for(int i=0;i<c;i++) { head=add_list(head,a[i]); } println(head); node *deNode=head; while(deNode->data!=7) { deNode=deNode->next; } node**Head; Head=&head; deletNode(Head,deNode); //删除值为7的结点 println(head); int a1=100; int *p1; p1=&a1; cout<<*p1<<endl; int **p2; p2=&p1; cout<<**p2<<endl; }
结果: