题解 | #牛牛的单向链表#

牛牛的单向链表

https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
}Node;

// 链表初始化
Node* initList() {
    Node* list = (Node*)malloc(sizeof(Node));
    list->data = 0;
    list->next = NULL;
    return list;
}


// 遍历链表
void printList(Node* list) {
    Node* head = list->next;
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

// 尾插法
void tailInsert(Node* list, int data) {
    Node* head = list;
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->next = NULL;
    
    while (head->next != NULL) {
        head = head->next;
    }
    head->next = node;
    list->data ++ ;
}

int main()
{
    int n; 
    scanf("%d", &n);

    Node* list = initList();

    for (int i = 0; i < n; i ++ )
    {
        int x;
        scanf("%d", &x);

        tailInsert(list, x);
    }

    printList(list);

    return 0;
}

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务