题解 | #遍历链表#
遍历链表
https://www.nowcoder.com/practice/7d348aa8b7d24e01a4f10bd023e2fb54
链表其实非常简单,主要是结构体的定义比较烦人,个人其实还是更加偏向用类的方式来实现,但是c没有,┭┮﹏┭┮
#include <stdio.h>
typedef struct node{
int val;
struct node* next;
} node;
int main() {
int n;
node* root = (node *)malloc(sizeof(node));
root->val = -9999;
node* pre = root;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int val;
scanf("%d", &val);
node* nd = (node *)malloc(sizeof(node));
nd->val = val;
if (val > pre->val) {
pre->next = nd;
pre = pre->next;
} else {
node* p = root;
while (p->next->val < val) {
p = p->next;
}
nd->next = p->next;
p->next = nd;
}
}
while (root->next) {
root = root->next;
printf("%d ", root->val);
}
printf("\n");
return 0;
}