仅仅是简单的实现,没有考虑程序的鲁棒性…
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} NODE;
// 尾插法(带头节点)
NODE *create_end()
{
NODE *head = (NODE *)malloc(sizeof(NODE));
head->next = NULL;
NODE *end = head;
int temp;
scanf("%d",&temp);
while (temp != 999) { // 当输入999时,表示链表数据输入完毕。
NODE *p = (NODE *)malloc(sizeof(NODE));
p->data = temp;
end->next = p;
end = p;
scanf("%d",&temp);
}
end->next = NULL;
return head;
}
// 头插法(带头节点)
NODE *create_head()
{
NODE *head = (NODE *)malloc(sizeof(NODE));
head->next = NULL;
int temp;
scanf("%d",&temp);
while (temp != 999) { // 注意:头插法所创建的链表,数据顺序和输入是相反的;
NODE *p = (NODE *)malloc(sizeof(NODE));
p->data = temp;
p->next = head->next;
head->next = p;
scanf("%d",&temp);
}
return head;
}
// 单链表打印
void print(NODE *head)
{
if (head == NULL) return;
NODE *p = head->next;
while (p != NULL) {
printf("%d\n", p->data);
p = p->next;
}
}
int main(int argc, const char * argv[]) {
NODE *head1 = create_end(); // 1
print(head1);
NODE *head2 = create_head(); // 2 ,可将1、2分别注释,观察打印效果。
print(head2);
return 0;
}