程序填空题:单链表的建立和输出
本题要求采用尾插法建立单链表并输出链表
```c
#include
#include
typedef int DataType;
struct Node {
DataType data;
struct Node* next;
};
typedef struct Node *PNode;
typedef struct Node *LinkList;
LinkList SetNullList_Link()
{
LinkList head = (LinkList)malloc(sizeof(struct Node));
if (head != NULL) head->next = NULL;
else printf("alloc failure");
return head;
}
void CreateList_Tail(struct Node* head)
{
PNode p = NULL; PNode q = head; int data;
scanf("%d", &data);
while (data != -1)
{
p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = NULL;
@@[q->next = p;
q = p;](4)
scanf("%d", &data);
}
}
void print(LinkList head)
{
PNode p = head->next;
while (p)
{
printf("%d ", p->data);
@@[p = p->next;](1)
}
}
void DestoryList_Link(LinkList head)
{
PNode pre = head;
PNode p = pre->next;
while (p)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
int main()
{
LinkList head = NULL;
head = SetNullList_Link();
CreateList_Tail(head);
print(head);
DestoryList_Link(head);
return 0;
}
```
答案:
第1空:q->next = p;
q = p;
第2空:p = p->next;
```c
#include
#include
typedef int DataType;
struct Node {
DataType data;
struct Node* next;
};
typedef struct Node *PNode;
typedef struct Node *LinkList;
LinkList SetNullList_Link()
{
LinkList head = (LinkList)malloc(sizeof(struct Node));
if (head != NULL) head->next = NULL;
else printf("alloc failure");
return head;
}
void CreateList_Tail(struct Node* head)
{
PNode p = NULL; PNode q = head; int data;
scanf("%d", &data);
while (data != -1)
{
p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = NULL;
@@[q->next = p;
q = p;](4)
scanf("%d", &data);
}
}
void print(LinkList head)
{
PNode p = head->next;
while (p)
{
printf("%d ", p->data);
@@[p = p->next;](1)
}
}
void DestoryList_Link(LinkList head)
{
PNode pre = head;
PNode p = pre->next;
while (p)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
int main()
{
LinkList head = NULL;
head = SetNullList_Link();
CreateList_Tail(head);
print(head);
DestoryList_Link(head);
return 0;
}
```
答案:
第1空:q->next = p;
q = p;
第2空:p = p->next;