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

牛牛的链表添加节点

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

#include <stdio.h>

typedef struct Node{
    int data;
    struct Node* next;
} node;
node* cai(int v){
    node* k = (node*)malloc(sizeof(node));
    k->data=v;
    k->next=NULL;
    return k;
}
void addn(node* head, int k) {
    if (k < 0) return;  // Handle negative k values
    
    node* new_node = cai(k);
    if (k == 0) {
        new_node->next = head;
        head = new_node;
        return;
    }

    node* current = head;
    for (int i = 1; i < k && current != NULL; i++) {
        current = current->next;
    }

    if (current != NULL) {
        new_node->next = current->next;
        current->next = new_node;
    }
}
int main(){
    int n,k;
    scanf("%d",&n);
    scanf("%d",&k);
    node* head=NULL;
    node* tail=NULL;
    for(int i=0;i<n;i++){
        int v;
        scanf("%d",&v);
        node* kk=cai(v);
        if(head==NULL){
            head=kk;
            tail=kk;
        }else{
            tail->next=kk;
            tail=kk;
        }
    }
    addn(head, k);
    node* p=head;
    while(p!=NULL){
        printf("%d ",p->data);
        p=p->next;
    }
}

全部评论

相关推荐

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