
每次将待插入的结点链在单链表的最后一个结点的后面
void creatlist(LinkList *LDatatype a[10])
{ L = (LinkList *) malloc (sizeof(struct node))
L->next = NULL //生成头结点
r = L //r为指向表尾的指针
for(i = 0i<=9i++)
{ p = (LinkList *) malloc (sizeof(struct node))
p->data = a[i] //生成新的结点
p->next = NULL
r->next = p //将新生成的结点插在表尾
r = p //将表尾指针指向新插入的结点
}
}
第一个问题:#include "stdio.h"
typedef struct lnode
{
int data
struct lnode *next
}lnode,*link
lnode *creat()用尾插入元素创建一个单链表函数;
{
link La,p,qint i,n
La=(link)malloc(sizeof(lnode))创建头结点
La->next=NULL
q=La
printf("input the number of element n:\n")
scanf("%d",&n)输入创建元素的个数n
for(i=1i<=n++i)
{
p=(link)malloc(sizeof(lnode))生成结点并用p指向
printf("input the value of %dth:\n",i)
scanf("%d",&p->data)输入元素的值
printf("\n")
q->next=pq=p
}
q->next=NULL将最后一个结点的next指向空
return (La)返回头结点的指针
}
void out(lnode *La)完成链表的输出函数
{
link p
p=La->next
printf("success output the every element:\n")
while(p)
{
printf("%d",p->data)
p=p->next
}
printf("\n")
}
void main()
{
lnode *Lc,*Ld
Lc=creat()
out(Lc)
}
我用的版本stdio里面包函了malloc函数,如果你用的没有的话,需在最前面引用到源程序文件中去;程序的功能是尾插入法创建一个大小由你输入的n的大小决定的一个带头结点的单链表;运行的时候,先提示你输入n,(n就是要创建的元素个数),然后提示你输入每个元素(由于为了方便,定义元素为int型,当你输入n个数后;则显示创建结果;
第二个问题:
#include "stdio.h"
typedef struct lnode
{
int data
struct lnode *next
}lnode,*link
lnode *creat()
{
link La,p,qint i,n
La=(link)malloc(sizeof(lnode))
La->next=NULL
q=La
printf("input the number of element n:\n")
scanf("%d",&n)
for(i=1i<=n++i)
{
p=(link)malloc(sizeof(lnode))
printf("input the value of %dth:\n",i)
scanf("%d",&p->data)
printf("\n")
q->next=pq=p
}
q->next=NULL
return (La)
}
void out(lnode *La)
{
link p
p=La->next
printf("success output the every element:\n")
while(p)
{
printf("%d",p->data)
p=p->next
}
printf("\n")
}
lnode *lizhi(lnode *Lb)与上一个程序不同之处是多了这个函数,实现单链表
{ lnode *p,*s的就地逆置;
p=Lb->next
Lb->next=NULL
s=p->next
while(p)
{
p->next=Lb->next
Lb->next=p
p=p->next
p=s
s=s->next
}
return (Lb)
}
void main()
{
lnode *Lc,*Ld
Lc=creat()
out(Lc)
Ld=lizhi(Lc)
out(Ld)
}
与上一个程序差不多,唯一不同的是多了一个逆置函数;
以上两个程序都可以成功运行的,你拿去试试吧,祝你成功。
#include <stdio.h>typedef struct student
{
int id
char name[20]
float score
}elemtype
elemtype stu[ ]={{1,"wang",78.0},{2,"zhang",80.0},{3,"li",86.0}}
typedef struct list_type
{
elemtype data[3]
int num
}listtype
int insert1 (listtype *l,int i,elemtype x)
int main()
{
int i
listtype lt
lt.num = 0
for (i=0i<3i++)
{
printf("%d,%s,%f",stu[i].id,stu[i].name,stu[i].score)
}
insert1(&lt, 0, stu[2])
insert1(&lt, 1, stu[1])
insert1(&lt, 2, stu[0])
printf("\nresult:\n")
for (i = 0i <lt.numi++)
{
printf("%d, %s, %f\n", lt.data[i].id, lt.data[i].name, lt.data[i].score)
}
return 0
}
# define true 0
# define false 1
int insert1 (listtype *l,int i,elemtype x)
{
int j
if (l->num>=3)
{
printf("the list is full,can not insert.")
return(false)
}
if ((i<0)||(i>l->num))
{
printf("i is invalid value")
return(false)
}
for (j=l->num-1j>=ij--)
l->data[j+1]=l->data[j]
l->data[i]=x
l->num++
return(true)
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)