#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} Node;
Node *CreateList()
{
Node *head = NULL;
Node *tail = NULL;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
Node *p = (Node *)malloc(sizeof(Node));
scanf("%d", &p->data);
p->next = NULL;
if (!head)
head = p;
if (tail)
tail->next = p;
tail = p;
}
return head;
}
void ShowList(Node *head)
{
while (head)
{
printf("%d ", head->data);
head = head->next;
}
}
void DestroyList(Node *head)
{
while (head)
{
Node *p = head;
head = head->next;
free(p);
}
}
int main()
{
Node *phead;
phead = CreateList();
ShowList(phead);
DestroyList(phead);
return 0;
}
供参考:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}Node;
Node* CreatList(int n)
{
Node* head = NULL, * p = NULL, * end = NULL;
head = (Node*)malloc(sizeof(Node));
head->next = NULL;
for (int i = 0; i < n; i++)
{
p = (Node*)malloc(sizeof(Node));
p->next = NULL;
//scanf("%d", &p->data);
p->data = i + 1;
if (i == 0)
head->next = p;
else
end->next = p;
end = p;
}
return head;
}
void ShowList(Node* phead)
{
for (phead = phead->next; phead != NULL; phead = phead->next)
printf("%d ", phead->data);
printf("\n");
}
int main(void)
{
Node* phead;
int n;
scanf("%d", &n);
phead = CreatList(n);
ShowList(phead);
return 0;
}