链式的线性表适用于经常进行删除,插入操作的工作,如:订票系统。
链表是用一个一个的节点连接起来的表,在物理上不是连续的,在逻辑上是连续的。通过节点间的指针指向来表示节点间的关系。
所以在进行链表操作之前,要先定义一个节点结构。节点结构包含两个东西:数据域,指针域。数据域就是用来存放数据的,指针域是用来表示节点间的关系。
第一步:定义链表节点
struct Node
{
int date; //数据域
struct Node *pNext; //指针域
};
定义好了节点之后,接下来就是定义链表初始化的方法。
第二步:初始化链表
struct Node *ListInit()
{
struct Node *head = (struct Node *)malloc(sizeof(struct Node));
if(NULL == head)
{
printf("malloc error!\n");
exit(-1);
}
head->pNext =NULL;
return head;
}
第三步:查看链表长度
int ListLen(struct Node *list)
{
struct Node *temp=list->pNext;
int count = 0;
while(NULL != temp)
{
count++;
temp = temp->pNext;
}
return count;
}
第四步:添加元素,因为链表的空间是动态分配,所以不存在满的情况,不用判满。
int ListAdd(struct Node *list,int elem)
{
struct Node *New = (struct Node *)malloc(sizeof(struct Node));
if(NULL == New)
{
printf("malloc error!\n");
exit(-1);
}
New->date = elem;
New->pNext = list->pNext;
list->pNext = New;
return 1;
}
第五步:删除元素,要判空
int ListEmpty(struct Node *list)
{
if(NULL != list->pNext)
return 0;
else
return 1;
}
然后定义删除元素的方法
int ListDel(struct Node *list, int pos)
{
int i = 1;
struct Node * p = list->pNext;
struct Node *temp = p;
if (NULL == p)
{
printf("链表为空,无法删除!\n");
return 0;
}
if (pos<1 || pos > ListLen(list))
{
printf("删除位置有误无法删除!\n");
return 0;
}
while (i!=pos)
{
i++;
temp = p;
p = p->pNext;
}
temp->pNext = p->pNext;
free(p);
return 1;
}
第六步:插入元素。
int ListInsert(struct Node *list,int pos,int elem)
{
struct Node *temp = list;
int i = 1;
if(pos < 1 || pos > ListLen(list)+1)
{
printf("插入位置有误无法插入!\n");
return 0;
}
while(i < pos)
{
temp= temp->pNext;
i++;
}
struct Node *New = (struct Node *)malloc(sizeof(struct Node));
if(NULL == New)
{
printf("malloc error!\n");
exit(-1);
}
New->date = elem;
New->pNext = temp->pNext;
temp->pNext = New;
return 1;
}
第七步:遍历表,输出信息。
void ListDisplay(struct Node *list)
{
struct Node *temp = list->pNext;
while(NULL != temp)
{
printf("%d,",temp->date);
temp = temp->pNext;
}
}
第九步:查找元素。
int ListFind(struct Node *list,int elem)
{
struct Node *temp = list->pNext;
int i = 1;
if(NULL == temp)
{
printf("表为空无法查找!\n");
return 0;
}
while(NULL != temp)
{
if(temp->date == elem)
{
return i;
}
temp = temp->pNext;
i++;
}
return 0;
}
链表其实很好理解,前提是要学会并理解指针,若看不懂的可先去学习下指针。