单链表的删除操作的实现(0953)swust-oj

#include<stdio.h>
#include<stdlib.h>
int total;
typedef struct node
{
int data;
struct node * next;
}Node;
void CreateNode(Node *&L,int a[],int n)//尾插法建立单链表
{
int i;
Node *p,*r;
L=(Node *)malloc(sizeof(struct node ));
p=L;
for(i=0;i<n;i++)
{
r=(Node *)malloc(sizeof(struct node));
r->data=a[i];
p->next=r;
p=r;
}
p->next=NULL;//尾节点制空
}
void NodeScan(Node *&L)//输入函数
{
int i;
scanf("%d",&total);
int a[1000];
for(i=0;i<total;i++)
{
scanf("%d",&a[i]);
}
CreateNode(L,a,total);//调用单链表
}
bool DeleteNode(Node *L,int i)
{
int j;
j=0;
Node *p=L,*q; //p指向头结点
while(j<i-1&&p) //查找第i-1个节点
{
j++;
p=p->next;
}
if(p==NULL) //没有找到第i-1个节点
return false;
else //找到第i-1个节点
{
q=p->next; //q指向第i个节点
if(q==NULL) //不存在第i个节点
{
return false;
}
p->next=q->next; //删除q节点
free(q);
return true;
}
}
void outputNode(Node*L)//输出函数
{
Node *read;//read指针,用来遍历输出
read=L->next;//指向头节点next
while(read->next)
{
printf("%d ",read->data);
read=read->next;
}
printf("%d",read->data);
}
bool InspectNode(Node *L,int i,int n)//判断输入的i是否合法
{
if(i!=1&&i<total)
{
return DeleteNode(L,i-1);
}
else
return false;
}
int main()
{
Node* L;
int i;
NodeScan(L);
scanf("%d",&i);
if(InspectNode(L,i,total))
{
outputNode(L);
}
else
printf("error!");
return 0;
}

原文地址:https://www.cnblogs.com/FENGXUUEILIN/p/4392863.html