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

牛牛的链表添加节点

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

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

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

node *createlist(){
    node *head = malloc(sizeof(node));
    if (head == NULL) {
        printf("out of memory");
        exit(1);
    }
    head->next = NULL;
    return head;
}
void add_node(node *head, int n, int *p)
{
    node *cur = head;   //声明一个尾指针跟踪插入新节点
    for (int i = 0; i < n; i++) {
    node *newnode = malloc(sizeof(node));
    if (newnode == NULL) {
        printf("out of memory");
        exit(1);
    }
    newnode->data = p[i];
    newnode->next = NULL;
    cur->next = newnode;
    cur = newnode;   //尾指针跟踪尾节点
    }
}
void insertnode(node *head, int i)
{
    node *q = head->next;     //声明一个流指针
    for (int j = 1; j < i; j++) {   //找到第i个节点
        q = q->next;     //虽然循环到j-1就不能再进入循环,但是它已经指向了下一个节点就是第i个节点
    }  
    //现在q指向第i个节点
    node *insertnode = malloc(sizeof(node));
    if (insertnode == NULL) {
        printf("out of memory");
        exit(1);
    } 
    insertnode->data = i;   //给要插入的节点赋值
    insertnode->next = q->next;   //进行插入
    q->next = insertnode;
}
int main() {
    int n, x;
    scanf("%d %d", &n, &x);
    int arr[n];
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    node *head = createlist();
    add_node(head,n, arr);
    insertnode(head,x);
    node *cur = head->next;
    while (cur != NULL) {
        printf("%d ", cur->data);
        cur = cur->next;
    }
    return 0;
}

全部评论

相关推荐

程序员猪皮:看不到八股什么意思
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务