单链表和顺序表同是属于线性表的范畴。
链表分为动态链表和静态链表。按照链表最原来的定义的,都是动态链表(这里都是动态链表)。根据每个结点所含指针的个数的不同,链表分为两大类,即单链表和多重链表;而根据指针的链接方式,又分为普通链表和循环链表。
以下内容针对最简单的链表形式,单链表
链表同样是一个结构体的形式存在的,基本的组成(对于单链表),就是一个指向下一个结点的结点指针,一个存储的数据内容(这个数据内容才是链表作为一个存储概念的意义和任务所在,而结点指针只是链表作为一个存储概念的内部组织结构)。
- 链表的结构形式为:
typedef struct{
elementype data;
struct node * next;
}node , chain_list;
node,表示的是,结点。chain_list,表示链表这个整体。
- 链表的基本操作也如下:
(同样,传入的参数,结构体必须是指针类型,函数里修改了到main也才有效)
void initChainList(chain_list * list,int n);
void print_ChainList(chain_list * list);
void insertNode(chain_list * list,int n,node * temp_node);
void clearChainList(chain_list * list);
void length_ChainList(chain_list * list);
int locatedtNode(chain_list * list,elementype datasearching);
void deleteNode(chain_list * list,elementype DatatoDelete);
void destroyChainList(chain_list * list);
- 具体函数的实现如下:
需要说明的是,因为里面极少有注释(这并不是个好习惯),有些代码觉得可能是多此一举,这些代码一般是为了处理特殊情况的,比如要删除的是头结点或者尾结点的话,可能前面的代码是没有考虑到这种情况的,所以就有一些·专门的代码来应对这种情况。(就是自己开发时,又要做开发,又要做测试,所以一定要考虑极端情况)而且代码的可读性和健壮性在实际开发中是很重要的(虽然我只实现了部分的健壮性hhh)。
其实,自己可能看不懂,如果自己实际上机写代码,就会清醒很多了。而且,面对报错,不应该是去规避它,而是应该去面对它。
void initChainList(chain_list * list,int n)函数:
void initChainList(chain_list * list,int n)
{
//一定要另外开一个list,不然原来的那个list,会错乱的 。
node * temp_list;
n--;
printf("into the func.\n");
temp_list = list;
for(;chainlist_length<n+1;chainlist_length++){
node * temp_node = (node *)malloc(sizeof(node));
if(!temp_node){
printf("temp_node_init is fail.\n");
return ;
}
temp_node->data = 11*(chainlist_length+1);
temp_node->next = NULL;
//循环到list的尾部,才能加上node
while(temp_list->next){
temp_list = temp_list->next;
}
temp_node->next = temp_list->next;
temp_list->next = temp_node;
//chainlist_length++;
}
}
void destroyChainList(chain_list * list):
void destroyChainList(chain_list * list)
{
while(list->next){
node * temp_node = list->next;
list->next = temp_node->next;
free(temp_node);
}
free(list);
printf("free all the node\n");
}
void deleteNode(chain_list * list,elementype DatatoDelete):
void deleteNode(chain_list * list,elementype DatatoDelete)
{
chain_list * temp_list;
temp_list = list;
int STATUS = 0;
while(temp_list->next){
node * temp = temp_list->next;
if(temp->data == DatatoDelete){
node * temp_node = temp_list->next;
temp_list->next = temp_node ->next;
free(temp_