单链表(带头结点)的删除

xiaoxiao2021-02-28  103

题目描述

1.问题描述

给出初始数据,实现单链表的定义、创建、查找和删除。假设单链表中的结点计数从1开始。

2.算法

单链表结点的存储结构包含两部分:数据、下一结点指针。

单链表的创建:依次为输入的数据分配结点,并按序链接起来。

单链表的查找:给出位置i,若第i个结点存在(1<=i<=表中结点数L),返回结点地址;否则,返回NULL。

单链表的删除:给出位置i,删除第i个结点(1<=i<=L)。

要求定义删除函数:int DeleteList(Node *H,int i) //删除第i个结点成功,返回1;第i个结点不存在,删除不成功,返回0。其中Node是链表结点结构体名,H是链表头指针。

输入

每个样本分2行:

第一行:第一个数字n表示样本数目,其后跟n个样本

第二行:删除测试次数m 后跟m个删除位置

输出

第一行:单链表创建后,输出链表中元素个数和单链表中的全部数据。

第二行至第m+1行:若删除指定位置的数据成功,输出链表中元素个数和单链表中的全部数据;若删除不成功,输出error。

样例输入

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; }
转载请注明原文地址: https://www.6miu.com/read-2150254.html

最新回复(0)