简单的列表

时间:2011-09-13 04:21:22

标签: c data-structures linked-list

我有以下单个链表,我总是得到1的长度,即使我推3个元素,也总是只创建一个节点。请帮忙。谢谢。

#include <stdio.h>

struct node
{
    int data;
    struct node *next;

};

void push(struct node **head,int data)
{
    struct node *temp = (struct node*)malloc(sizeof(struct node));
    temp->data=data;
    if(*head == NULL)
    {
        *head=temp;

    }
    else
    {
    temp->next=*head;
    *head=temp;

    }
}

int length(struct node *head)
{
    struct node *temp = head;
    int count=0;
    if(temp !=NULL)
    {
        count++;
        printf("%d",temp->data);
        temp=temp->next;
    }
    return count;
}
int main()
{
    int a;
    struct node *head=NULL;
    push(&head,1);
    push(&head,2);
    push(&head,3);

    a=length(head);
    printf("%d",a);
    return 0;
}

5 个答案:

答案 0 :(得分:5)

在长度函数

中将if替换为while

答案 1 :(得分:2)

length功能中,更改此行:

if(temp !=NULL)

到此:

while(temp != NULL) 

答案 2 :(得分:1)

您是否注意到长度方法的结构?您正在使用if语句,其中循环是合适的。你得到1的答案,因为你只执行一次count ++语句。

希望这有帮助。

答案 3 :(得分:1)

错误来自push()函数。如果head不为null,则需要将列表迭代到最后一个节点。正如while之前所说的那样if

答案 4 :(得分:0)

# include <stdlib.h>

void push(struct node **head,int data)
{
struct node *temp;

temp = malloc (sizeof *temp);

temp->data = data;
temp->next = *head;
*head = temp;
} 
相关问题