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

牛牛的链表添加节点

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

#include <stdio.h>
#include <stdlib.h>
#define N 100

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

struct Node* createList(int *arr,int n)
{
    struct Node *head = NULL, *tail = NULL;
    for(int i = 0; i < n; i++)
    {
        struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode -> data = arr[i];
        newNode -> next = NULL;
        if(head == NULL)
        {
            head = newNode;
            tail = newNode;
        }
        else 
        {
            tail -> next = newNode;
            tail = newNode;
        }
    }

    return head;
}


void addNode(struct Node *head,int index)
{
    struct Node *p = head;
    int count = 1;//记录当前是第几个节点;
    //找到插入节点的前一个节点
    while (p != NULL && count < index)
    {
        p = p -> next;
        count++;
    }

    if(p != NULL)
    {
        struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode -> data = index;
        newNode -> next = p -> next;
        p -> next = newNode;
    }

}

void printList(struct Node *head)
{
    struct Node *p = head;
    while(p != NULL)
    {
        printf("%d ",p -> data);
        p = p -> next;
    }
}

int main()
{
    int n,index;
    scanf("%d %d",&n,&index);
    int arr[N];
    for(int i = 0; i < n; i++)
    {
        scanf("%d",&arr[i]);
    }

    struct Node *head = createList(arr,n);

    addNode(head,index);

    printList(head);

    return 0;
}

全部评论

相关推荐

2025-12-16 22:45
已编辑
电子科技大学 活动运营
Rain_Codin...:简历感觉有点乱了而且一股AI味,AI简历的一个特点就是废话很多,一个点能分成四个点来讲,可以仔细优化一下。 btw,手机看简历不好看出来,可以把电脑上的简历截图放出来。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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