数据结构C++如何用template建立一个含有n个元素的单循环链表?

里面元素按照1,2,3,4,5,6......,n排列。
2024-12-16 12:43:02
推荐回答(2个)
回答1:

关于# include 问题你看看这个
我将你代码改了点就没的错误了,代码如下:
# include
#include
struct Worker
{
int num;
float pay;
struct Worker *next;
};
int n;

int main()
{
struct Worker *head,*create(void);
void list(struct Worker*);
head=create();
list(head);
return 0;
}

struct Worker *create(void)
{
struct Worker *head, *p1, *p2;
printf("create a linked list:\n");
head=0;
n=0;
p1=p2=(struct Worker*)malloc(sizeof(struct Worker));
scanf("%d%f",&p1->num,&p1->pay);
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else p2->next=p1 ;
p2=p1;
p1=(struct Worker*)malloc(sizeof(struct Worker)) ;
scanf("%d%f",&p1->num,&p1->pay);
}
p2->next=0;
free(p1);
return head;
}

void list(struct Worker *p)
{
printf("The linked list:\n");
while( p!=0 )
{
printf("\n%\t%f",p->num,p->pay);
p=p->next;
}
}

另外,站长团上有产品团购,便宜有保证

回答2:

关于# include 问题你看看这个
我将你代码改了点就没的错误了,代码如下:
# include
#include
struct Worker
{
int num;
float pay;
struct Worker *next;
};
int n;

int main()
{
struct Worker *head,*create(void);
void list(struct Worker*);
head=create();
list(head);
return 0;
}

struct Worker *create(void)
{
struct Worker *head, *p1, *p2;
printf("create a linked list:\n");
head=0;
n=0;
p1=p2=(struct Worker*)malloc(sizeof(struct Worker));
scanf("%d%f",&p1->num,&p1->pay);
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else p2->next=p1 ;
p2=p1;
p1=(struct Worker*)malloc(sizeof(struct Worker)) ;
scanf("%d%f",&p1->num,&p1->pay);
}
p2->next=0;
free(p1);
return head;
}

void list(struct Worker *p)
{
printf("The linked list:\n");
while( p!=0 )
{
printf("\n%\t%f",p->num,p->pay);
p=p->next;
}
}