/*参考资料:数据结构(c语言版) 黄国瑜*/
#include <stdlib.h>
#include <stdio.h>
struct List /* 节点结构声明 */
{
int num;
struct List *next;
};
typedef struct List *link;
/*由数组建立链表*/
link link_create(link head, int* data, int size)
{
int i;
link tail;
link new1;
if (data == NULL || size <= 0)
return NULL;
for (i=0; i<size; i++)
{
new1 = (link)malloc(sizeof(struct List));
new1->num = data[i];
new1->next = NULL;
if ( head == NULL)
{
head = new1;
tail = new1;
}
else
{
tail->next = new1;
tail = new1;
}
}
return head;
}
/*链表反转*/
link link_revert(link head)
{
link newhead, node;
if(head == NULL || head->next == NULL)
return head;
newhead = NULL;
while(head)
{
node = head;
head = head->next;
node->next = newhead;
newhead = node;
}
return newhead;
}
/*链表链接*/
link link_connect(link head1, link head2)
{
link head_tail;
if(head1 == NULL && head2 == NULL)
return NULL;
else if(head1 == NULL && head2 != NULL)
return head2;
head_tail = head1;
while(head_tail->next != NULL)
head_tail = head_tail->next;
head_tail->next = head2;
return head1;
}
/*链表比较*/
int link_compare(const link head1, const link head2)
{
link p1,p2;
if( head1 == NULL && head2 == NULL)
return 1;
else if(head1 == NULL || head2 == NULL)
return 0;
p1 = head1;
p2 = head2;
while(p1->num == p2->num)
{
p1 = p1->next;
p2 = p2->next;
if(p1 == NULL && p2 == NULL)
return 1;
else if(p1 == NULL || p2 == NULL)
return 0;
}
return 0;
}
/*链表查找*/
int link_search(const link head, int key)
{
link tmp = head;
while(tmp)
{
if (key == tmp->num)
return 1;
tmp = tmp->next;
}
return 0;
}
/*链表打印*/
void link_print(const link head)
{
link tmp = head;
while(tmp)
{
printf("%d ", tmp->num);
tmp = tmp->next;
}
printf("\n");
}
/*链表释放*/
void link_free(link head)
{
link tmp;
while(head)
{
tmp = head;
head = head->next;
free(tmp);
}
}
void main ()
{
int input[] = {6,8,5,93,485,365,254,369};
int input2[] ={6,8,5,93,485,365,254,369,9};
int search_num = 0;
link head = NULL;
link head2 = NULL;
head = link_create(head, input, sizeof(input)/sizeof(input[0]));
link_print(head);
printf("search data:%d\n", link_search(head, search_num));
head2 = link_create(head2, input2, sizeof(input2)/sizeof(input2[0]));
link_print(head2);
printf("link compare:%d\n", link_compare(NULL, NULL));
head = link_revert(head);
link_print(head);
head2 = link_connect(head, head2);
link_print(head2);
link_free(head);
return 0;
}
单链表及其相关操作
最新推荐文章于 2022-05-04 11:03:21 发布