删除单链表中第i个节点,用e返回被删除的元素
1个回答
展开全部
#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef int Status;
typedef struct Lnode {
ElemType data;
struct Lnode *next;
}Lnode,*LinkList;
//以下是建立单链表
void creatlist(LinkList &head)
{
//请将该算法补充完整
head=new Lnode;
LinkList q;
q=head;
for(int i=1;i<10;++i)
{
LinkList p;
p=new Lnode;
p->data=i;
p->next=NULL;
q->next=p;
q=p;
}
}
// 删除以 L 为头指针(带头结点)的单链表中第 i 个结点
Status ListDelete_L(LinkList L, int i, ElemType &e) {
//请将该算法补充完整
LinkList p;
int j=0;
while(L)
{
p=L->next;
++j;
if(j==i)
{
L->next=p->next;
e=p->data;
delete p;
return OK;
}
L=L->next;
}
return ERROR;
}
//以下是输出单链表
void output(LinkList L){
LinkList p = L->next;
if(p==NULL){
printf("\n No list\n");
return;
}
while (p) {
printf("%4d",p->data);
p = p->next;
}
printf("\n");
}
void main( ){
LinkList L; int i;
ElemType e;
int st;
printf("\n creat of the list:\n");
creatlist(L);
printf("\n output list before deleting:\n");
output(L);
printf("input i=");
scanf("%d", &i);
st=ListDelete_L(L, i, e);
if (st==0) printf("\n i is illogical:\n");
else {
printf("deleted e=%d",e);
printf("\n output list after deleting:\n");
output(L);
}
}
#include "stdlib.h"
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef int Status;
typedef struct Lnode {
ElemType data;
struct Lnode *next;
}Lnode,*LinkList;
//以下是建立单链表
void creatlist(LinkList &head)
{
//请将该算法补充完整
head=new Lnode;
LinkList q;
q=head;
for(int i=1;i<10;++i)
{
LinkList p;
p=new Lnode;
p->data=i;
p->next=NULL;
q->next=p;
q=p;
}
}
// 删除以 L 为头指针(带头结点)的单链表中第 i 个结点
Status ListDelete_L(LinkList L, int i, ElemType &e) {
//请将该算法补充完整
LinkList p;
int j=0;
while(L)
{
p=L->next;
++j;
if(j==i)
{
L->next=p->next;
e=p->data;
delete p;
return OK;
}
L=L->next;
}
return ERROR;
}
//以下是输出单链表
void output(LinkList L){
LinkList p = L->next;
if(p==NULL){
printf("\n No list\n");
return;
}
while (p) {
printf("%4d",p->data);
p = p->next;
}
printf("\n");
}
void main( ){
LinkList L; int i;
ElemType e;
int st;
printf("\n creat of the list:\n");
creatlist(L);
printf("\n output list before deleting:\n");
output(L);
printf("input i=");
scanf("%d", &i);
st=ListDelete_L(L, i, e);
if (st==0) printf("\n i is illogical:\n");
else {
printf("deleted e=%d",e);
printf("\n output list after deleting:\n");
output(L);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询