数据结构中的表为线性结构,一般分为顺序表和链式表。其中链式表用一组相连的结点存储数据,链式表又分为带头结点的和不带头结点的,不带头结点的链表在进行会影响表结构的操作时需要用二级指针,带头结点的比较通用。下面我们详细说带头结点的链式表:
先给 int 类型起个别名(非必要)
#define TYPE int
现在我们来创建链式表的结构体
typedef struct Node
{
TYPE data;
struct Node *next;
}Node;
下面我们开始写顺序表的相关运算算法:
创建
//创建
Node *create_list(TYPE data)
{
Node *node=malloc(sizeof(Node));
node->data=data;
node->next=NULL;
return node;
}
头添加
//头添加
void add_head_list(Node *head,TYPE data)
{
Node *node=create_list(data);
node->data=data;
node->next=head->next;
head->next=node;
head->data++;
}
尾添加
//尾添加
void add_tail_list(Node *head,TYPE data)
{
Node *node=create_list(data);
node->data=data;
for(Node *n=head;;n=n->next)
{
if(NULL==n->next)
{
node->next=n->next;
n->next=node;
break;
}
}
head->data++;
}
按位置删除
//按位置删除
bool del_index_list(Node *head,int index)
{
while(--index>0)
{
head=head->next;
if(NULL==head->next) return false;
}
Node *temp=head->next;
head->next=temp->next;
free(temp);
return true;
}
按值删除
//按值删除
void del_value_list(Node *head,TYPE val)
{
for(Node *n=head->next;n->next;n=n->next)
{
if(n->next->data==val)
{
Node *temp=n->next;
n->next=temp->next;
free(temp);
}
}
head->data--;
}
插入
//插入
bool insert_list(Node *head,int index,TYPE val)
{
while(--index>0)
{
head=head->next;
if(NULL==head->next) return false;
}
Node *node=create_list(val);
node->data=val;
node->next=head->next;
head->next=node;
return true;
}
修改
//修改
bool modify_list(Node *head,TYPE old,TYPE new)
{
for(Node *n=head->next;n->next;n=n->next)
{
if(n->data==old)
{
n->data=new;
return true;
}
}
return false;
}
访问
//访问
bool access_list(Node *head,int index,TYPE *val)
{
while(--index>0)
{
head=head->next;
if(NULL==head) return false;
}
*val=head->data;
return true;
}
排序
//排序
void sort_list(Node *head)
{
for(Node *i=head->next;i->next;i=i->next)
{
for(Node *j=i->next;j;j=j->next)
{
if(j->data>i->data)
{
TYPE temp=i->data;
i->data=j->data;
j->data=temp;
}
}
}
}
查询
//查询
int query_list(Node *head,TYPE key)
{
int num=1;
for(Node *n=head;n->next;n=n->next,num++)
{
if(n->data==key) return num;
}
}
遍历
//遍历
void show_list(Node *head)
{
for(Node *n=head;n;n=n->next)
{
printf("%d ",n->data);
}
}
在主函数里调用这些函数来测试一下:
int main(int argc,const char* argv[])
{
Node *head=create_list(0);
for(int i=0;i<10;i++)
{
//add_head_list(head,rand()%100);
add_tail_list(head,rand()%100);
}
show_list(head);
printf("\n");
if(del_index_list(head,1)) head->data--;
show_list(head);
printf("\n");
//del_value_list(head,15);
if(insert_list(head,4,66)) head->data++;
show_list(head);
printf("\n");
sort_list(head);
modify_list(head,66,88);
show_list(head);
TYPE a;
TYPE *a1=&a;
access_list(head,7,a1);
printf("\n%d\n",a);
int place=query_list(head,88);
printf("%d\n",place);
show_list(head);
return 0;
}
over
1万+

被折叠的 条评论
为什么被折叠?



