单链表中的结果不正确

时间:2014-01-09 00:38:00

标签: c singly-linked-list

程序编译,但是当我创建列表并尝试显示它时,我输入的内容不一样,所以我猜我的代码有问题。因此,如果有人可以指出它的错误并且可能纠正错误:

struct client
{
    char name[30];
    struct client *next;
};

struct client* FindTailClient(struct client* head)
{
    while( head->next != NULL)
    {

        head = head->next;
    }
    return head;
}

struct client* AddClient(struct client** head, char name[])
{
    struct client* newnode =malloc(sizeof(struct client));
    if (newnode == NULL) {
        fprintf(stderr, "failed to allocate memory.\n");
        return -1;
    }
    newnode->next = NULL;
    strcpy(newnode->name,name);
    if(*head == NULL)
    {
        *head = newnode;
    }
    else
    {
        struct client* node = FindTailClient(*head);
        node->next = newnode;
    }
}

void Display(struct client *head)
{
    struct client *current = head;
    while (current != NULL)
    {
        printf("%s",current->name);
        current = current->next;
    }
}

int main()
{
    int i;
    struct client *head ;


    char name[30];
    for (i = 0; i < 5; i++)
    {
        scanf("%s",name);
        AddClient(head,name);
    }
    Display(head);
}

3 个答案:

答案 0 :(得分:1)

在AddClient()中,您声明struct client **head,但是您正在向其传递struct client *

删除额外的星号(将**更改为*并在AddClient中将*head更改为head)它应该可以正常工作。或者,将&head传递给AddClient(),尽管我看不出有任何理由指向指向列表头部的指针。

答案 1 :(得分:0)

我认为从指针指针(**)到指针的改变不会起作用。从主要地址传递头部的地址应该有效。

答案 2 :(得分:0)

在查找客户端中

不要将头节点指向null创建临时节点,而将其指向null。 像这样

struct client *find_client(struct client *head) {
    struct client *temp = head;

    while (temp->next != NULL) {
        temp =temp->next;    
    }

    return temp;
}

我们不必让头脑走到尽头我们必须走到尽头。