线性表的这两种存储结构是后面其他数据结构的基础。至关重要
若是我们在初始化链表时,不想直接添加数据,那么我们就需要使用到头结点。
若是我们不想用到头结点,那么我们需要在开始初始化数据的时候就带上数据。
Status InitList(CLinkList* L,int n)
{
CLinkList rear, q; //rear是尾结点
ElemType item;
rear = q = NULL;
srand(time(0));
for (int i = 0; i < n;i++)
{
item = rand() % 100;
printf("%d ", item);
if (*L==NULL)
{
*L = (CLinkList)malloc(sizeof(Node));
if (!(*L))
return ERROR;
(*L)->data = item;
(*L)->next = *L; //自己指向自己
rear = *L; //设置尾指针位置
}
else
{
//生成新的节点,根据尾指针添加节点,并实时更新尾指针。注意这里数据插入是尾插法
q = (CLinkList)malloc(sizeof(Node));
q->data = item;
q->next = rear->next;
rear->next = q;
rear = q;
}
}
printf("
");
return OK;
}