# 单链表（带头结点）的删除

xiaoxiao2021-02-28  109

1.问题描述

2.算法

## 样例输入

5 2 4 3 5 7 3 0 2 4

## 样例输出

5 2 4 3 5 7 error 4 2 3 5 7 3 2 3 5

// // Created by HP on 2018/3/9. // #include <iostream> using namespace std; struct node{ int num; node *next; }; int n; void CreateList(node *head) { node *tail=head; int data; int i; for(i=0;i<n;i++){ cin>>data; node *s=new node;//创建新的节点 s->num=data; s->next=NULL; tail->next=s;//将新结点插入链表中 tail=s; } } void ShowList(node *head) { cout<<n; node *display=head->next; while(display){ cout<<" "<<display->num; display=display->next; } cout<<endl; } int Deletelist(node *head,int dn) { if(dn>0&&dn<=n){ n--; node *p,*pre; pre=head; p=head->next; int count=1; while(p){ if(count==dn){ pre->next=p->next; delete(p); p=NULL; return 1; } count++; pre=pre->next; p=p->next; } } return 0; } int main() { int t; cin>>n; node *head=new node; head->next=NULL; CreateList(head);//创建 ShowList(head);//输出 cin>>t; while(t--){ int dn; cin>>dn; if(Deletelist(head,dn))//删除 ShowList(head);//输出 else cout<<"error"<<endl; } return 0; }