| 单向链表函数表 |
---|
1 | create_Forward_list//创建头节点 |
2 | insert_Node//插入新节点 |
3 | delete_Node//删除节点 |
4 | find_by_order//查找,返回第order位的指针 |
5 | find_by_value//按值查找,返回指针 |
6 | Forward_list_Length//返回链表的长度 |
#include<stdio.h>
#define ElementType int
struct Forward_list;
typedef struct Forward_list* PtrToNode;
typedef PtrToNode forward_list;
forward_list create_Forward_list();
void insert_Node(forward_list s, int order, ElementType value);
void delete_Node(forward_list s, int order);
PtrToNode find_by_order(forward_list s, int order);
PtrToNode find_by_value(forward_list s, int value);
int Forward_list_Length(forward_list s);
struct Forward_list
{
PtrToNode next;
ElementType Element;
};
int main()
{
forward_list my_list = create_Forward_list();
insert_Node(my_list, 1, 1);
insert_Node(my_list, 2, 2);
insert_Node(my_list,3 ,3);
delete_Node(my_list,2);
printf("%d",my_list->next->Element);
printf("%d",my_list->next->next->Element);
}
forward_list create_Forward_list()
{
forward_list s;
s = (PtrToNode)malloc(sizeof(struct Forward_list));
if (s == NULL)
{
std::cerr << "out of space";
return NULL;
}
s->next = NULL;
return s;
}
void insert_Node(forward_list s, int order, ElementType value)
{
PtrToNode walker;
PtrToNode finded_Ptr = find_by_order(s, order);
forward_list new_Node = (PtrToNode)malloc(sizeof(struct Forward_list));
if (new_Node == NULL) {
printf("out of space");
return;
}
for (walker = s; walker->next != finded_Ptr; walker = walker->next)
{
}
walker->next = new_Node;
new_Node = walker->next;
new_Node->Element = value;
walker->next->next = NULL;
}
void delete_Node(forward_list s, int order)
{
PtrToNode walker;
PtrToNode finded_Ptr = find_by_order(s, order);
if (finded_Ptr == NULL)
{
printf("erro in order");
return;
}
forward_list new_Node = (PtrToNode)malloc(sizeof(struct Forward_list));
if (new_Node == NULL) {
printf("out of space");
return;
}
for (walker = s; walker->next != finded_Ptr; walker = walker->next)
{
}
if (walker != NULL)
{
walker->next = finded_Ptr->next;
finded_Ptr = NULL;
free(finded_Ptr);
}
}
PtrToNode find_by_order(forward_list s, int order)
{
PtrToNode walker = s;
if (order > Forward_list_Length(s) + 1)
{
printf( "please input the right order<<endl");
return NULL;
}
for (int i = 1; i <= order; i++)
{
walker = walker->next;
}
return walker;
}
PtrToNode find_by_value(forward_list s, int value)
{
PtrToNode walker;
for (walker = s; walker != NULL; walker = walker->next)
{
if (walker->Element == value)
{
return walker;
}
}
printf("did't find it");
return NULL;
}
int Forward_list_Length(forward_list s)
{
PtrToNode walker;
int cnt = 0;
for (walker = s->next; walker != NULL; walker = walker->next)
{
cnt++;
}
return cnt;
}