删除线性表中第i个数据元素

#include"stdio.h"
#include"malloc.h"
# define null 0
struct lnode {
int data;
struct lnode * next;
}

main()
{ int x,y,i=1,n,d;
char yesorno;
struct lnode *head, *p,*q,*r;
head = null;
q = null;
head = ( struct lnode *) malloc (sizeof( struct lnode));
head->next=null;
printf("请您输入一列正整数,并按0结束输入:\n");
scanf("%d",&d);
while( d > 0 )
{ p = ( struct lnode *) malloc (sizeof( struct lnode));
p->data = d;
p->next = null;
if(head->next ==null) head->next=p;
else q->next = p;
q = p;
scanf("%d",&d);
}
printf("您输入的链表为:");
q=head;
while(q->next!=null)//输出链表
{ printf("%d",q->next ->data );
q = q->next;}
printf("\n");
//2、 在线性表中值为x的元素前插入一个值为y的数据元素。若值为x的结点不存在,则将y插在表尾。
printf("请输入x和y的值,并用空格隔开:");
scanf("%d%d",&x,&y);

r=( struct lnode *) malloc (sizeof( struct lnode));
r->data=y;
r->next=null;
q=head;
while(q->next!=null&&q->next->data !=x)q = q->next;
r->next=q->next;
q->next=r;

q=head;
printf("插入数据y后的链表为:");
while(q->next!=null)//输出链表
{ printf("%d",q->next ->data );
q = q->next;}
printf("\n");

//3、删除线性表中第i个数据元素。

printf("您要删除的元素是第几位:\n");
scanf("%d",&n);
q=head;
while(i!=n)
{
if(q->next==null)break;
q=q->next;

i++;
}
if(q->next)
{

r->next=q->next;
q->next=r;
}
q=head;
while(q->next!=null)//输出链表
{ printf("%d",q->next ->data );
q = q->next;}
printf("\n");

}

就是最后一部分删除的,我写的不对,不知道怎么写了~

#include"stdio.h"
#include"malloc.h"
# define null 0
struct lnode {
int data;
struct lnode * next;
};

int main()
{
int x, y, i = 1, n, d;
char yesorno;
struct lnode *head, *p, *q, *r;
head = null;
q = null;
head = (struct lnode *) malloc(sizeof(struct lnode));
head->next = null;
printf("请您输入一列正整数,并按0结束输入:\n");
scanf("%d", &d);
while (d > 0)
{
p = (struct lnode *) malloc(sizeof(struct lnode));
p->data = d;
p->next = null;
if (head->next == null) head->next = p;
else  q->next = p;
q = p;
scanf("%d", &d);
}
printf("您输入的链表为:");
q = head;
while (q->next != null)//输出链表
{
printf("%d", q->next->data);
q = q->next;
}
printf("\n");
//2、 在线性表中值为x的元素前插入一个值为y的数据元素。若值为x的结点不存在,则将y插在表尾。
printf("请输入x和y的值,并用空格隔开:");
scanf("%d%d", &x, &y);

r = (struct lnode *) malloc(sizeof(struct lnode));
r->data = y;
r->next = null;
q = head;
while (q->next != null&&q->next->data != x)q = q->next;
r->next = q->next;
q->next = r;

q = head;
printf("插入数据y后的链表为:");
while (q->next != null)//输出链表
{
printf("%d", q->next->data);
q = q->next;
}
printf("\n");

//3、删除线性表中第i个数据元素。

printf("您要删除的元素是第几位:\n");
scanf("%d", &n);
q = head;
i = 1; // 初始化 i = 1
while (i != n)
{
if (q->next == null) break;
q = q->next;

i++;
}
if (q->next)
{

r = q->next; // 被删的是r
q->next = r->next;
free(r);
}
q = head;
while (q->next != null)//输出链表
{
printf("%d", q->next->data);
q = q->next;
}
printf("\n");
}

温馨提示:答案为网友推荐,仅供参考
相似回答