- 注册时间
- 2004-10-13
- 最后登录
- 2019-5-15
⑧专业
*永恒国度*
- 积分
- 14145
|
#include<stdio.h>
#include<stdlib.h>
struct list
{
char data;
struct list *next;
}*head;
setnull(struct list **p) //置空
{
*p=NULL;
}
int length(struct list **p) //求链表的长度
{
int n=0;
struct list *q=*p;
while(q!=NULL)
{
n++;
q=q->next;
}
return n;
}
void insert(struct list **p,char x,int i)//插入元素
{
int j=1;
struct list *s,*q;
s=(struct list *)malloc(sizeof(struct list));
s->data=x;
s->next=NULL;
q=*p;
if(i==1)
{
s->next=q;
*p=s;
}
else
{
while(j<i-1&&q->next!=NULL)
{
q=q->next;
j++;
}
if(j==i-1)
{
if(q->next!=NULL)
{
s->next=q->next;
q->next=s;
}
else
{
q->next=s;
}
}
else
printf("位置不正确.");
}
}
void del(struct list **p,int i)//删除链表中的元素
{
int j=1;
struct list *t,*q;
q=*p;
if(i==1)
{
t=q;
*p=q->next;
}
else
{
while(j<i-1&&q->next!=NULL)
{
q=q->next;
j++;
}
if(j==i-1)
{
t=q->next;
q->next=t->next;
}
else
printf("位置不对.");
}
if(t!=NULL)
free(t);
}
void display(struct list **p)//显示链表中的元素
{
struct list *q;
q=*p;
printf("单链表显示:");
if(q==NULL)
printf("链表为空!");
else if(q->next==NULL)
printf("%c",q->data);
else
{
while(q->next!=NULL)
{ printf("%c-",q->data);
q=q->next;
}
printf("%c",q->data);
}
printf("\n");
}
void main()
{
setnull(&head);
insert(&head,'a',1);
insert(&head,'c',2);
insert(&head,'b',2);
display(&head);
del(&head,1);
display(&head);
}
在删除元素的这一个部分
void del(struct list **p,int i)//删除链表中的元素
{
int j=1;
struct list *t,*q;
q=*p;
if(i==1)
{
t=q;
*p=q->next;
}
else
{
while(j<i-1&&q->next!=NULL)
{
q=q->next;
j++;
}
if(j==i-1)
{
t=q->next;
q->next=t->next;
}
else
printf(\"位置不对.\");
}
if(t!=NULL)
free(t);
}
为什么当删除一位置的这个元素时一定要写成这样
if(i==1)
{
t=q;
*p=q->next;
}
其实删除位置是一的话,只需要这一句就行了, *p=q->next; 为什么还要加上一句 t=q; 呢?
把这句去掉了,就不行了,到底为什么会这样呢?这句 t=q; 又是什么意思呢? |
|