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

牛牛的链表添加节点

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

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

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

//头结点
node* creatnode(int val){
    node *p = (node*)malloc(sizeof(node));
    if(p == NULL)
    {
        return NULL;
    }
    p->data = val;
    p->next = NULL;
    return p;
}

//插入节点
void insertnode(node* p, int val){
    node * q = (node*)malloc(sizeof(node));
    if(q == NULL){
        return;
    }
    q->data = val;
    q->next = NULL;
    // node* tmp = p->next;
    // while(tmp != NULL){
    //     tmp = tmp->next;
    // }
    p->next = q;
}
//打印

void printfnode(node* p){
    node* head = p;
    
    while(head->next != NULL){
        printf("%d ",head->data);
        head = head->next;
    }
}
//插入节点
void istnode(node* p, int num){
    node* head = p;
    node* new = (node*)malloc(sizeof(node));
    
    // while()
    for(int i=1;i<num; i++)
        head = head->next;
       
    new->data = num;
    new->next = head->next;
    head->next = new;
        
    
} 


// void istnode(node* p, int num){
//     node *head = p;
//     for(int i=0;i<num;i++){
//         head = head->next;

//     }
// }


int main() {
    // int a, b;
    // while (scanf("%d %d", &a, &b) != EOF) { // 注意 while 处理多个 case
    //     // 64 位输出请用 printf("%lld") to 
    //     printf("%d\n", a + b);
    // }
    int a, b;
    scanf("%d %d", &a, &b);
    node* head = creatnode(0);
    
    int *arr = (int*)malloc(sizeof(int)*a);

    for(int i=0; i<a;i++){
        scanf("%d",&arr[i]);
        // insertnode(head, num);
    }
    head->data = arr[0];
    node *p = head;
    for(int j=1;j<=a;j++){
        insertnode(p, arr[j]);
        p = p->next;
    }
    istnode(head, b);
    printfnode(head);


    return 0;
}

#悬赏#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 15:58
投个小米提前批试试水,先投一个岗位看看形势,不行就再沉淀一下投第二个岗位,莫辜负
Java抽象带篮子:我嘞个骚刚,已经开始研发6g了吗
投递小米集团等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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