您的位置:首页 > 理论基础 > 数据结构算法

SDUT1138数据结构上机测试2-1:单链表操作A

2016-07-21 18:35 543 查看
此题坑点在对末尾节点的操作,避免指针越界

#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
}*head,*tail,*q,*p;
int n,key;
void built()
{
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(int i=0; i<n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
tail->next=p;
tail=p;
}
tail->next=NULL;
}
void print()
{
p=head->next;
while(p)
{
printf("%d",p->data);
if(p->next)
printf(" ");
p=p->next;
}
}
void del()
{
p=head;
while(p->next)
{
if(p->next->data==key)
{
if(p->next->next==NULL)
{
p->next=NULL;
n--;
break;
}
p->next=p->next->next;
n--;
}
p=p->next;
}
}
int main()
{
scanf("%d",&n);
built();
scanf("%d",&key);

printf("%d\n",n);
print();
del();
printf("\n%d\n",n);
print();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: