我正在尝试实现链表抽象,但是我遇到了问题。一旦我创建了链接列表并向其中添加元素。当我打印列表时,它仅以无限循环方式打印其中的第一个元素,这意味着第一个元素链接到其自身或打印函数不正确。但是我找不到问题所在,有人可以帮忙吗?
以下是列表抽象:
typedef struct _friend {
char *firstname;
char *lastname;
char birthdate[9];
} friend;
typedef struct _node {
friend *value;
struct _node *next;
} node;
typedef struct _linkedlist {
node *head;
} linkedlist;
程序必须遵循这种抽象,因为它是更大事物的一部分。 以下是应打印列表并将节点添加到列表开头的函数:
/* addHead
*
* This function takes two parameters - a linked list and a friend.
* This creates a node for the linked list and connects the friend to the
* node. Then it adds the node to the head of the linked list.
*/
void addHead(linkedlist *llist, friend *f)
{
// create a node and put the friend in it
node *n = (node *)malloc(sizeof(node));
n->value = f;
n->next = NULL;
// if the list is empty
if (llist == NULL)
{
// this link is the entire list
llist->head = n;
printf("adding friend to null list\n");
}
// if the list is not empty
else
{
// make the new link's next pointer point to
// the first link in the list
n->next = llist->head;
printf("adding %s to head\n", n->value->firstname);
// make the head pointer point to the new link
llist->head = n;
}
}
/*
* printList
*
* This steps down through each of the nodes in a linked list and
* prints out the information stored in the friend to which the node points.
* Instead of automatically printing to the screen, it prints to the
* file pointer passed in. If the programmer wants to print to the screen,
* he/she will pass in stdout.
*/
void printList(linkedlist *llist,FILE *fp)
{
node *n;
friend *f;
// for each node, print out the friend attached to it
for(n = llist->head; n != NULL ; n = llist->head->next)
{
// assign f to the friend of the right node
f = n->value;
// print the friend out
fprintf(fp,"%s %s: %s\n",
f->firstname, f->lastname, f->birthdate);
}
}
谢谢
最佳答案
printList
中的 for
循环不太正确:
for(n = llist->head; n != NULL ; n = llist->head->next)
这应该是:
for(n = llist->head; n != NULL ; n = n->next)
否则从第二次迭代开始,n
每次都会设置为相同的值。
以下内容与您遇到的问题无关,但我想我还是要提一下。在下面的代码中:
if (llist == NULL)
{
// this link is the entire list
llist->head = n;
printf("adding friend to null list\n");
}
如果llist == NULL
,llist->head = n
将会出现段错误。
使用 addHead()
的当前签名,如果 llist
为 NULL
(除了打印错误),您无能为力消息并退出)。
如果您想检查 llist->head
是否为 NULL,则不需要这样做,因为 else
block 已经正确处理了该问题。
关于c - C 中的链表,链表构造正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9007875/