题解 | #牛牛的链表添加节点#

牛牛的链表添加节点

https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a

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

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

Node* creatList() {
    Node* head = (Node*)malloc(sizeof(Node));
    head->next = NULL;
    return head;
}

void addNode(Node* head, int data) {
    Node* p = head;
    Node* q = (Node*)malloc(sizeof(Node));
    while (p->next != NULL) {
        p = p->next;
    }
    q->data = data;
    p->next = q;
    q->next = NULL;
}

void addi(Node* head, int data) {
    Node* p = head;
    Node* q = (Node*)malloc(sizeof(Node));
    for (int i = 0; i < data; i++) {
        p = p->next;
    }
    q->data = data;
    q->next = p->next;
    p->next = q;
}

void print(Node* head) {
    Node* p = head->next;
    while (p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
}
int main() {
    Node* head = creatList();
    int n, x;
    scanf("%d%d", &n, &x);
    for (int i = 0; i < n; i++) {
        int a;
        scanf("%d", &a);
        addNode(head, a);
    }
    addi(head, x);
    print(head);
    return 0;
}

全部评论

相关推荐

面试拷打成m:我感觉他说的挺对的,感觉我找不到工作也要去送外卖了,至少饿不死
点赞 评论 收藏
分享
牛客48826091...:哥们胸肌挺好看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务