链表的头文件以及一些简单的应用(二)

2014-11-23 23:24:36 · 作者: · 浏览: 16
);
next = (nodetype *)malloc(sizeof(nodetype));
next->data = temp;
cur->next = next;
cur = next;
list->length++;
}
cur->next = NULL;
return list;
}
listtype * list_insert(listtype *list, int location, int data)
{
nodetype *temp, *cur;
cur = list->head;
if (location > 0 && location <= list->length)
{
while(--location)
cur = cur->next;
node_insert(cur, data);
}
else if(location == 0)
{
temp = (nodetype *)malloc(sizeof(nodetype));
temp->data = data;
temp->next = list->head;
list->head = temp;
}
else
{
error(3);
}
list->length++;
return list;
}
nodetype * node_delete(nodetype *cur, nodetype *pre)
{
pre->next = cur->next;
free(cur);
return pre;
}
int list_delete(listtype *list, int data)
{
nodetype *cur, *pre;
for (cur = list->head, pre = NULL;
cur->data != data && cur != NULL;
pre = cur, cur = cur->next)
;
if (cur == NULL)
{
printf("Can't find the data!\n");
return 0;
}
else if(cur != list->head)
{
node_delete(cur, pre);
}
else if(cur == list->head)
{
list->head = cur->next;
free(cur);
}
list->length--;
return data;
}
listtype * list_delete_node(listtype *list, nodetype *node)
{
nodetype *pre;
if (node == list->head)
{
list->head = node->next;
free(node);
list->
length--;
}
else
{
pre = list->head;
while(pre->next != node)
pre = pre->next;
node_delete(node, pre);
}
return list;
}
nodetype * list_add(listtype *list, int data)
{
nodetype *cur, *temp;
for (cur = list->head;
cur != NULL && cur->next != NULL;
cur = cur->next)
;
temp = (nodetype *)malloc(sizeof(nodetype));
temp->data = data;
temp->next = NULL;
if (list->length == 0)
list->head = temp;
else
cur->next = temp;
list->length++;
return temp;
}
void error(int err)
{
switch(err)
{
case 1:
printf("RAM error!\n");
break;
case 2:
printf("Length error!\n");
break;
case 3:
printf("Location error!\n");
break;
default:
printf("Unknown error!\n");
}
exit(EXIT_FAILURE);
}
以下是一些功能的测试:
test.c:
[cpp]
#include
#include "list.h"
int main(void)
{
listtype *list;
int length, location, data;
list = list_create();
for (;;)
{
printf("Please input the length of the list:");
scanf("%d", &length);
if (length <= 0)
break;
list_input(list, length);
list_print(list);
}
for (;;)
{
printf("Please input the data you want to insert:");
scanf("%d", &data);
print