本篇博客主要介绍带头结点的单链表的一系列操作,包括链表的创建,链表的插入,链表的删除,链表的查找,判断一个链表是否为空,以及在写程序的时候一些注意事项等内容。链表是数据内容的基础,学好了,后面栈就比较容易了。本文用一个可以运行的完整的程序来例举了上述所有的内容,程序中也标明了每个程序的功能。大家可以对照链表的基础知识以及本文所给出的程序进行学习。话不多少,直接给出程序:
#include <stdio.h>
#include <stdlib.h>
struct Node;
typedef struct Node* ptrToNode;
typedef ptrToNode List;
typedef ptrToNode Position;
typedef int ElementType;
typedef struct Node
{
ElementType element;
Position next;
}Node;
//create a list
List createList(int *ptr, int len)
{
List head;
Position p;
Position tmp;
head = malloc(sizeof(struct Node));
p = malloc(sizeof(struct Node));
int i = 0;
for(; i < len; i++)
{
if (i == 0)
{
p -> element = *(ptr + i);
head -> next = p;
}
else
{
tmp = malloc(sizeof(struct Node));
tmp -> element=*(ptr+i);
p -> next = tmp;
p = p->next;
}
}
p -> next = NULL;
return head;
}
//test if a list is empty or not
int IsEmpty(List L)
{
return L->next == NULL;
}
Position FindPrevious(ElementType X, List L)
{
Position p;
p = L;
while(p->next != NULL && p->next->element != X)
p = p ->next;
return p;
}
void Delete(ElementType X, List L)
{
Position previous;
Position pnow;
previous = FindPrevious(X,L);
if(IsEmpty(previous))
{
printf("Sorry, there is no %d in the list!\n", X);
exit(1);
}
else
{
pnow = previous -> next;
previous -> next = pnow -> next;
free(pnow);
}
}
void prinList(List L)
{
Position p = L -> next;
printf("The list is: \n");
while(p->next != NULL)
{
printf("%d ",p -> element);
p = p -> next;
}
printf("\n");
}
void InsertList(ElementType X, Position P, List L)
{
Position temp;
temp =malloc(sizeof(struct Node));
if (!temp)
{
printf("Out of space!\n");
exit(1);
}
temp -> element = X;
temp -> next = P -> next;
P -> next = temp;
}
int main()
{
int a[10] = {12,4354,657,876,2433,23,18,943,54,8};
List L = malloc(sizeof(struct Node));
L = createList(a,10);
if(IsEmpty(L))
{
printf("The list is empty!\n");
exit(1);
}
prinList(L);
Delete(a[1],L);
prinList(L);
InsertList(a[1],L->next,L);
prinList(L);
return 0;
}
在anycodes在线编程网站上的运行结果:
注意事项:
1. 注意指针变量的初始化;
2.何时使用或何时不使用malloc创建单元?
我的理解是在链表中,比如在插入操作中,对于这个即将被插入进链表的单元不可能凭空而来,所以肯定要用malloc进行创建。例外,声明指向一个结构体的指针并不会创建该结构,而只是给出足够的空间容纳结构可能会使用的地址。创建未被声明过的记录的唯一方法是使用malloc函数;
3. 何时需要free?
在删除操作中,进行一次删除之后,再讲该单元释放通常是一个非常好的做法。
本篇博客到此结束,下期博客,栈。有事请留言。