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

牛牛的单向链表

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

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

// 定义链表节点结构
struct ListNode {
    int val;
    struct ListNode *next;
};

// 创建一个新的链表节点
struct ListNode* createNode(int val) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = val;
    newNode->next = NULL;
    return newNode;
}

// 打印链表
void printList(struct ListNode *head) {
    struct ListNode *current = head;
    while (current != NULL) {
        printf("%d ", current->val);
        current = current->next;
    }
    printf("\n");
}

int main() {
    int n;
    
    // 输入数组的长度
    scanf("%d", &n);
    
    // 输入数组的值
    int *arr = (int *)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // 创建链表
    struct ListNode *head = NULL;
    struct ListNode *tail = NULL;
    for (int i = 0; i < n; i++) {
        struct ListNode *newNode = createNode(arr[i]);
        if (head == NULL) {
            head = newNode;
            tail = newNode;
        } else {
            tail->next = newNode;
            tail = newNode;
        }
    }

    // 打印链表
    printList(head);

    // 释放内存
    struct ListNode *current = head;
    while (current != NULL) {
        struct ListNode *temp = current;
        current = current->next;
        free(temp);
    }
    free(arr);
    
    return 0;
}

全部评论

相关推荐

牛客771574427号:恭喜你,华杰
点赞 评论 收藏
分享
10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务