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

牛牛的链表添加节点

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

#include <stdio.h>
#include <stdlib.h>
//结构体
typedef struct Node
{
    int num;
    struct Node *next;    
}LinkNode;
//创建链表
LinkNode *creat_link(int n){
    int i;
    LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));
    LinkNode *tail;
    head->next = NULL;
    scanf("%d", &head->num);
    tail = head;
    for (i = 0; i < n-1; ++i)
    {
        LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
        scanf("%d", &p->num);
        p->next = NULL;
        tail->next = p;
        tail = tail->next;
    }
    return head;
}
//插入链表
LinkNode *insertNode(LinkNode *head,LinkNode *ptr,int value){
    LinkNode *newnode=(LinkNode *)malloc(sizeof(LinkNode));
    if(!newnode)return NULL;
    newnode->num = value;
    newnode->next = NULL;
    if(ptr==NULL){
        newnode->next=head;
        return newnode;
    }else{
        if(ptr->next==NULL)ptr->next=newnode;
        else{
            newnode->next=ptr->next;
            ptr->next=newnode;
        }
    }
    return head;
}

int main(int argc, char const *argv[])
{
    int n,i;
    scanf("%d", &n);
    int num;
    scanf("%d", &num);
    LinkNode *head = creat_link(n);
    LinkNode *tail,*ptr;
    tail = head;
    while(i<=num+1){
        ptr = tail;
        tail = tail->next;
        i++;
    }
//     printf("%d\n", ptr->num);
    tail = head;
    head = insertNode(head, ptr, num);
//打印链表
    while(tail != NULL){
        printf("%d ", tail->num);
        tail = tail->next;
    }
    printf("\n");
    return 0;
}
全部评论

相关推荐

09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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