题解 | #牛牛的单向链表#
牛牛的单向链表
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++刷题的题解思路