最近开始学习数据结构相关的知识,看到单链表的内容,对于单链表的创建的头插法和尾插法两种方法,又根据单链表是否带有头结点,这样会产生四种情况。作为刚刚开始学习数据结构的小白,很是迷茫,通过参考《大话数据结构》等,现在对单链表的创建做一个总结,以备日后复现。如果下面的内容有错误,还请多多指出。
typedef struct LNode{
int data;
struct LNode * next;
}LNode;
typedef LNode* List;
//用头插法创建带有头结点的单链表
LNode * Createhead1(int length)
{
int data[12] ={0,1,2,3,4,5,6,7,8,9,10,11}; //为了测试方便,自己写了数组来测试,也可以用下面的随机数来创建
LNode * p;
//srand(time(0)); // 初始化随机数种子
if(length < 1)
return NULL;
LNode *head = (LNode*)malloc(sizeof(LNode));
head->next = NULL;
int i = 1;
while(i<=length)
{
p = (LNode*)malloc(sizeof(LNode));
//p->data = rand()%100+1; //随生成100以内的数字
p->data = data[i];
p->next = head->next;
head->next = p;
i++;
}
return head;
}
//头插法无头结点创建
LNode *Createhead2(int length)
{
int data[12] ={0,1,2,3,4,5,6,7,8,9,10,11};
LNode*p;
//srand(time(0));
if(length<1)
return NULL;
LNode *first = (LNode*)malloc(sizeof(LNode));
first->next = NULL;
first->data = data[0];
int i = 1;
while(i<length)
{
p = (LNode*)malloc(sizeof(LNode));
//p->data = rand()%100+1;
p->data = data[i];
p->next = first;
first = p;
i++;
}
return first;
}
//尾插法带头结点创建
LNode*Createrail1(int length)
{
int data[12] ={0,1,2,3,4,5,6,7,8,9,10,11};
LNode *p;
//srand(time(0));
if(length<1)
return NULL;
LNode *head =(LNode*)malloc(sizeof(LNode));
head->next = NULL;
LNode *temp = head;
int i = 1;
while(i<=length)
{
p = (LNode*)malloc(sizeof(LNode));
//p->data = rand()%100+1;
p->data = data[i];
temp->next = p;
temp = p;
i++;
}
temp->next = NULL;
return head;
}
//尾插法无头结点创建
LNode * Createrail2(int length)
{
int data[12] ={0,1,2,3,4,5,6,7,8,9,10,11};
LNode *p;
//srand(time(0));
if(length<1)
return NULL;
LNode *first = (LNode*)malloc(sizeof(LNode));
first->next = NULL;
first->data = data[0];
LNode * temp = first;
int i =1;
while(i<length)
{
p = (LNode*)malloc(sizeof(LNode));
//p->data = rand()%100+1;
p->data = data[i];
temp->next =p;
temp = p;
i++;
}
temp->next = NULL;
return first;
}
void PrintL(List L)
{
List p = L->next; //当测试带头结点的单链表,采用这句;
//List p = L; //当测试无头结点的单链表,采用这句;
if(!p)
{
return;
}
while(p)
{
printf("%d ",p->data);
p = p->next;
}
}