c语言(双链表中插入节点问题),就在查找到的sp后面插入新节点。

c语言(双链表中插入节点问题),就在查找到的sp后面插入新节点。,第1张

#include

<stdlib.h>

#include

<stdio.h>

#include

<conio.h>

#include

<string.h>

typedef

struct

dl

{

char

name[20]

struct

dl

*prior,*next

}stud

stud

*creat(int

n)

{

stud

*p,*h,*s

int

i

h=(stud*)malloc(sizeof(stud))

h->name[0]=NULL

h->prior=NULL

h->next=NULL

p=h

for(i=0i<ni++)

{

s=(stud*)malloc(sizeof(stud))

p->next=s

printf("Input

the

%d

student's

name:",i+1)

scanf("%s",s->name)

s->prior=p

s->next=NULL

p=s

}

p->next=NULL

return

h

}

stud

*search(stud

*h,char

*x)

{

stud

*p

char

*y

p=h->next

while(p)

{

y=p->name

if(strcmp(y,x)==0)

return

p

else

p=p->next

}

printf("Cannot

find

name!")

return

NULL//没有返回NULL

}

stud

*insert(stud

*h,char

*ps)

{

stud

*p,*s

p=h->next

while(p->next!=NULL)//寻找最后节点

p=p->next

s=(stud*)malloc(sizeof(stud))//建立新节点

strcpy(s->name,ps)

s->next=NULL

if(p!=NULL)//存在末尾节点,插入末尾

{

p->next=s

}

else//否则,视为第一个节点,插入

表头

后面

h->next=s

return

s

}

void

main()

{

int

n

char

sname[20]

stud

*head,*sp,*sert

printf("Please

input

the

size

of

the

list:")

scanf("%d",&n)

head=creat(n)

sp=head->next

printf("The

double

list

is:\n")

while(sp)

{

printf("%s

",sp->name

)//直接写成sp->name,以下同

sp=sp->next

}

printf("\nPlease

input

the

name

which

you

want

to

find:")

scanf("%s",sname)

sp=search(head,sname)

if(sp!=NULL)//

非空

,显示

printf("The

name

you

want

to

find

is:%s\n",sp->name)

else//没有插入

sert=insert(head,sname)

sp=head->next

printf("\nNow

the

double

list

is:\n")

while(sp)

{

printf("%s

",sp->name)

sp=sp->next

}

getch()

}

画图就明白了。

翻译一下这串代码:让A后面的节点的前面节点等于B,让B的后面一个节点等于A后面的一个节点,让A的后面的节点等于B,让B前面的一个节点等于A。

先处理A后面的一个节点,使其与B连接,然后再让A和B连接


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11588918.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存