习题3.1
编写打印出一个单链表的所有元素的程序。
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
struct Node {
struct Node* next;
int data;
};
Node* findLast(Node* list) {
while (list->next) {
list = list->next;
}
return list;
}
void insert(Node*list, int a) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = a;
p->next = NULL;
Node* q = findLast(list);
q->next = p;
}
int main() {
Node *list = (Node*)malloc(sizeof(Node));
list->next = NULL;
int a;
while (scanf_s("%d", &a) == 1)
insert(list, a);
Node* p = list->next;
while (p) {
printf("%d", p->data);
p = p->next;
}
system("pause");
return 0;
}