BUPT-homework/semester2/pset1/3-appendLinkedList.c

61 lines
1,010 B
C
Raw Permalink Normal View History

2022-03-08 20:36:51 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct link {
int data;
struct link *next;
} * Link;
Link AppendNode(Link head, int data);
void DisplyNode(Link head);
int main() {
int data;
Link head = NULL;
while (1) {
scanf("%d", &data);
if (data == -1)
break;
head = AppendNode(head, data);
}
if (head != NULL)
DisplyNode(head);
else
printf("NULL");
return 0;
}
/*在此实现 AppendNode函数 */
Link AppendNode(Link head, int data) {
if (head == NULL) {
head = malloc(sizeof(Link));
head->next = NULL;
head->data = data;
} else {
Link ptr = head;
while (ptr->next != NULL) {
ptr = ptr->next;
}
Link next = malloc(sizeof(Link));
ptr->next = next;
next->next = NULL;
next->data = data;
}
return head;
}
/*在此实现DisplyNode函数 */
void DisplyNode(Link head) {
printf("%d", head->data);
Link ptr = head->next;
while (ptr != NULL) {
printf(",%d", ptr->data);
ptr = ptr->next;
}
}