获取链表的长度

时间:2017-10-12 04:33:44

标签: c list

typedef struct _node *Node;
typedef struct _list *List;

typedef struct _list {
    Node head;
} list;

typedef struct _node {
    int value;
    Node next;
} node;

int listLength (List l);

int ListLength (List l) {

    /* Insert code here */ 

    return result; //replace this
}

嘿,我是链接列表的新手,我不确定如何检查列表的长度。我打算创建一个可以执行此操作的函数,但我不确定如果列表只包含(节点头)而不包含(节点下一个),列表是如何移动的。

1 个答案:

答案 0 :(得分:2)

试试这个

int listLength (List l) {
    int len = 0;
    Node n = l->head;
    while(n != NULL){
        len++;
        n = n->next;
    }
    return len;
}

插入元素时,必须将其下一个设置为NULL!

Node createNode(int val){
    Node n = malloc(sizeof(node));
    n->value = val;
    n->next = NULL;
    return n;
}

void add(int val, List l){
    if(l->head == NULL){
        l->head = createNode(val);
    } else {
        Node n = l->head;
        while(n->next != NULL){
            n = n->next;
        }
        n->next = createNode(val);
    }
}

对于malloc,您必须包含stdlib #include<stdlib.h>