【发布时间】:2015-06-16 04:20:45
【问题描述】:
我正在尝试在 C 中创建一个循环链表。 但是我对链表还不是很了解。 好吧,程序将一个 int 传递给一个名为 list_end_ptr 的函数,该函数初始化循环链表并为该 int 创建节点。 然后另一个函数(insert_at_end)将新节点放在初始化列表的末尾并返回最后一个节点。 第三个函数通过获取结束节点并首先打印第一个输入的名称并以最后一个结束来打印链接列表(print_list)。
这个想法是只有一个结束节点并且只使用它,但我不能让它工作。我设法使它部分工作,当我打印时,数据以名称条目的相反顺序打印(从最后输入到第一个)。
有什么想法吗?
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define SIZE 10
#define NUM_PER_LINE 3
typedef struct node
{
char name[SIZE]; /* SIZE-1 χαρακτήρες και το '\0' */
struct node * next;
} CListNode;
void get_name(char *a);
void print_list(CListNode *end_ptr);
CListNode *initiate(int n);
CListNode *insert_at_end(CListNode *end_ptr, char *a);
int main(void) {
CListNode *list_end_ptr;
int n=6;
list_end_ptr=initiate(n);
print_list(list_end_ptr);
return 0;
}
void get_name(char *a)
{
char format[10];
sprintf(format, "%%%ds", SIZE-1);
scanf(format, a);
}
CListNode *insert_at_end(CListNode *end_ptr, char *a)
{
CListNode *temp, *head=NULL;
head=end_ptr->next;
temp=(CListNode *) malloc(sizeof(CListNode));
end_ptr->next=temp;
strcpy(temp->name, a);
temp->next=head;
return temp;
}
CListNode *initiate(int n) {
CListNode *end, *first=NULL;
int i;
char new_name;
end=(CListNode *) malloc(sizeof(CListNode));
if (end==0) {
printf("Allocation error...\n");
exit(0); }
end->next=end;
for (i=0; i<n; i++) {
if (i<1) {
printf("Enter the name of the %d person: ", i+1);
get_name(&new_name);
strcpy(end->name, &new_name);
first=end;
}
else
{
printf("Enter the name of the %d person: ", i+1);
get_name(&new_name);
insert_at_end(end, &new_name);
}
}
return end;
}
void print_list(CListNode *end_ptr)
{
int i=1;
CListNode *str_ptr;
if (end_ptr == NULL)
printf("\n List is empty");
else
{
str_ptr = end_ptr->next;
while (str_ptr != end_ptr)
{
printf("%s \t", str_ptr->name);
str_ptr = str_ptr->next;
if (i%NUM_PER_LINE==0) {
printf("\n");
}
i++;
}
printf("%s\n", str_ptr->name);
}
}
【问题讨论】:
标签: c linked-list