C语言实现单向链表

#include<stdio.h>
  
struct Node{
    int data;
    Node *next;
};

int count = 0;

int enqueueNode(Node *head, int data){

    //定义一个空node,代表链表中的下一个node元素
    Node *node = (Node *)malloc(sizeof(Node));
    if(node == NULL){
        return 0;
    }
    node->data = data;
    node->next = NULL;

    //定义一个指向head node的指针
    Node *p = head;
    while(p->next != NULL){
        p = p->next;
        count++;
        printf("count = %d\n",count);
    }
    p->next = node;
    return 1;

}

int main(int argc, const char * argv[]) {
    int num = 10;
    int i = 0;
    //定义一个单链表
    Node *list;
    list = (Node *)malloc(sizeof(struct Node));
    list->data = 0;
    list->next = NULL;
    for(i = 0; i<num; i++)
        enqueueNode(list, i+1);
    }
    while (list->next != NULL) {
        printf("data = %d \n", list->data);
        list = list->next;
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容