单链表及其相关操作

/*参考资料:数据结构(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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值