|
发表于 2013-7-14 15:19:09
|
显示全部楼层
#include <stdio.h>
#include <stdlib.h>
#define NULL 0
#define LEN sizeof(struct Lnode)
struct Lnode //链表的节点类型
{
int data;
struct Lnode *next;
};
struct Lnode * deletep(struct Lnode *h,int i)//该子函数作用为删除链表h的第i个节点,刚进原来函数有些问题,我自己修改了一下,修改的部分增加了备注
{
int j=1;
struct Lnode *q,*p;
p=h->next;//修改,p初始化为指向首节点
if(i==1) //i为1,删除的是首节点
{
h-next=p->next;//修改,头结点指向了原链表的首节点的下一个节点
free(p);//释放原首节点
}
else //删除的为第i个节点
{
while((j<i-1)&&(NULL != (p-next)))//修改,循环找到第i-1节点并用p指向它
{
p=p->next;
j++;
}
if(p!=NULL)//找到了该节点
{
q = p; //新增,记录第i-1个节点的位置
p = p->next;//新增,p指向第i个节点
q->next=p->next;//用第i-1节点的指针域指向第i+1个节点
free(p);//是否第i个节点
}
}
return h;
}
void main()
{
struct Lnode *p,*q,*head;
int l,len=0;
p=(struct Lnode *)malloc(LEN);//动态生成一个struct Lnode类型节点(第1个一般用做头节点,便于链表操作),并用p指针指向该节点
head=NULL;
printf("input num:\n");
scanf("%d",&p->data);// 对上面新生成的头节点的int部分输入数值,
while(p->data!=0) //当节点中int部分不为0时,循环生成链表中的新节点
{
p->next=NULL;
if(head==NULL){head=p;q=p;}//head指向新生成的头节点
else //生成新节点后添加进链表,q是指向链表尾部的,p指向新节点
{
q->next=p;
q=p;
}
len++;//链表计数增加,此处应该不包含头节点
p=(struct Lnode*)malloc(LEN);//生成节点,p指向
scanf("%d",&p->data);//给节点输入值
}
printf("input the position:");
scanf("%d",&l);
if(l>len||l<=0)//对l的合法性进行判读
{
printf("error,input please");
printf("\n");
return;
}
head=deletep(head,l);//调用子函数删除链表中的第l个节点
len--;//删除后链表中节点个数减一
printf("the new list:");
p=head;//将头节点的位置赋给p
for(l=0;l<=len-1;l++)//循环输出节点的值
{
printf("%3d",p->data);
p=p->next;
}
}
|
|