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()

}

加分了

#include<stdio.h>

#include<stdlib.h>

class point //节点类

{

public:

int a //节点值

point *next//next指针

}

void newlast(point *&p,int i) //在*p所指的链表的最后新建一个值为i的节点

{

point *q,*o

q=p

while(q->next)

{

q=q->next

}

printf("%d\n",q->a)

o=(point *)malloc(sizeof(point))

o->a=i

q->next=o

o->next=NULL //结束标记

}

void show(point *p)//输出指针p所指链表

{

point *q

q=p

while(q)

{

printf("%d\t",q->a)

q=q->next

}

printf("\n")

}

int main()

{

point b1,b2,b3

point *p

b1.a=1

b2.a=2

b3.a=3

p=&b1

b1.next=&b2

b2.next=&b3

b3.next=NULL //结束标记

show(p)

newlast(p,4)

show(p)

return 0

}


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

原文地址: https://outofmemory.cn/bake/11755356.html

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

发表评论

登录后才能评论

评论列表(0条)

保存