用表头创建单链表,用头插法创建链表,遍历的结果是9 8 7 6 5 4 3 2 1
具体的源程序如下:
#include <stdio.h>
#include <stdlib.h>
#define OK 0
#define ERROR -1
#define MALLOC_ERROR -2
typedef int ElementType;
typedef struct node
{
ElementType data;
struct node *next;
}Node;
typedef Node *PNode;
int Create_List_Head(PNode h, ElementType data)
{
if (h == NULL)
{
return ERROR;
}
PNode node = (PNode)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
return MALLOC_ERROR;
}
node->data = data;
node->next = h->next;
h->next = node;
return OK;
}
void DisPlay(PNode h)
{
if (h == NULL)
{
return;
}
PNode temp = h->next; // 链表第一个结点指针
while (temp)
{
printf ("%4d", temp->data);
temp = temp->next;
}
printf ("\n");
}
int main()
{
PNode head_node = (PNode)malloc(sizeof(Node)/sizeof(char));
if (head_node == NULL)
{
return ERROR;
}
head_node->next = NULL;
int i = 1;
for (i = 1; i < 10; i++)
{
if (Create_List_Head(head_node, i) != OK)
{
return ERROR;
}
}
DisPlay(head_node);
return 0;
}