题解 | #遍历链表#
遍历链表
https://www.nowcoder.com/practice/7d348aa8b7d24e01a4f10bd023e2fb54
#include <stdio.h> typedef struct Node { int value; struct Node* next; } Node; int main() { int n; while (scanf("%d ", &n) != EOF) { // 注意 while 处理多个 case //带头节点 Node* head = (Node*)malloc(sizeof(Node)); Node* newNode, *p, *pre; head->value = 0; head->next = NULL; int newValue; for (int i = 0; i < n; i++) { //创建新节点 newNode = (Node*)malloc(sizeof(Node)); scanf("%d ", &newValue); newNode->value = newValue; newNode->next = NULL; //头插法 if (i == 0) { head->next = newNode; } else { pre = head; p = head->next; while (p != NULL && newValue > p->value) { pre=pre->next; p=p->next; } newNode->next=p; pre->next=newNode; } } p=head->next; while(p!=NULL){ printf("%d ",p->value); p=p->next; } printf("\n"); } return 0; }