题解 | #牛牛的单向链表#

牛牛的单向链表

https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4

#include <cstddef>
#include <cstdlib>
#include <iostream>
using namespace std;
#define OK 1
typedef int Status;

typedef struct Node{
    int num;
    Node *next = NULL;
}LNode, *LList;

Status initList(LList *lst)
{
    (*lst) = (LNode*)malloc(sizeof(LNode));
    (*lst)->next = NULL;
    return OK;
}

void insert(LList lst, int num)
{
    LNode *p = lst;
    while (p != NULL && p->next != NULL)
        p = p->next;
    LNode *t = (LNode*)malloc(sizeof(LNode));//开辟新的内存空间
    t->num = num;
    t->next = NULL;
    p->next = t;    
}

int main() {
    int n;
    cin >> n;
    int num;
    LList lst;
    initList(&lst);
    for (int i = 0; i < n; ++i)
    {
        cin >> num;
        insert(lst, num);
    }
    LNode *p = lst->next;
    while (p != NULL)
    {
        cout << p->num << " ";
        p = p->next;
    }
        

}
// 64 位输出请用 printf("%lld")

使用尾插法插入链表的元素。记得链表元素要不断往后移动。这里定义了一个虚拟头结点。

C++题解 文章被收录于专栏

记录在牛客网用C++刷题的题解思路

全部评论

相关推荐

身边有人上海、深圳&nbsp;6、7k&nbsp;都去了,真就带薪上班了。
程序员小白条:木的办法, 以后越来越差,还是家附近宅着吧,毕业的人越来越多,岗位都提供不出来,经济又过了人口红利期
点赞 评论 收藏
分享
06-22 10:41
赣东学院 Java
程序员小白条:?周六晚上投,这是什么操作,专门找996起步的吗
点赞 评论 收藏
分享
强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
码农索隆:有点耳熟,你们是我教过最差的一届
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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