c语言 单链表 (有头链表)2020-12-10

#include <stdio.h>
#include <stdlib.h>

struct node
{
	int val;
	int hao;
	struct node *next;
};

void showlist(struct node *h)//遍历
{
	printf("============\n");
	while(h->next)
	{
		printf("hao %d  val %d\n", h->next->hao, h->next->val);
		h = h->next;
	}
}

void insert_head(struct node *h, struct node *n)//头插
{
	n->next = h->next;
	h->next = n;
}
void insert_Head(struct node **h, struct node *n)//头插
{
	n->next = *h;
	*h = n;
}

void insert_tail(struct node *h, struct node *n)//尾插
{
	while(h->next)
	{
		h = h->next;
	}
	h->next = n;
}
void insert_Tail(struct node **h, struct node *n)//尾插
{
	while((*h))
	{
		h = &((*h)->next);
	}
	*h = n;
}

struct node* find_list(struct node *h, int n, struct node newlist)//查找
{
	
	while(h->next->val == n)
	{
		struct node *tmp = h->next;
		h->next = h->next->next;
		tmp->next = NULL;
		insert_tail(&newlist, tmp);
	}

	struct node *p = h->next;
	while(p->next)
	{
		if(p->next->val == n)
		{
			struct node *t = p->next;
			struct node *tmp = p->next;
			p->next = t->next;
			tmp->next = NULL;
			insert_tail(&newlist, tmp);
		}else
		{
			p = p->next;
		}
	}
	return newlist.next;
}
struct node* sort_list(struct node *h, struct node newsort)//排序
{
	struct node *p = h->next;
	struct node *min = NULL;
	struct node *minprev = NULL;
	struct node *t = NULL; 
	while(p)
	{
		minprev = NULL;
		t = p;
		min = t;
		while(t->next)
		{
			if(min->val > t->next->val)
			{
				minprev = t;
				min = t->next;
			}else
			{
				t = t->next;
			}
		}
		if(min == p)
		{
			p = p->next;
		}else
		{
			minprev->next = min->next;
		}
		min->next = NULL;
	//	insert_head(&newsort, min);
		insert_tail(&newsort, min);
	}
	return newsort.next;
}
void destroy(struct node **h)
{
	struct node *p = NULL;
	while(*h)
	{
		p = (*h)->next;
		free(*h);
		*h == NULL;
		*h = p;
	}
}
int main ()
{
	struct node head;
	int arr[] = {8,8,1,2,8,3,8,8,4,8,8};
	int i = 0;
	struct node *newnode = NULL;
	head.next = NULL;
	while(i < sizeof(arr)/sizeof(int))
	{
		newnode = malloc(sizeof(struct node));
		newnode->val = arr[i];
		newnode->hao = i;
		newnode->next = NULL;
//		insert_head(&head, newnode);
//		insert_head(&(head.next), newnode);
		
//		insert_tail(&head, newnode);
		insert_Tail(&(head.next), newnode);
				
		i++;
	}
	showlist(&head);

//	struct node newlist;
//	newlist.next = NULL;
//	newlist.next = find_list(&head, 8, newlist);
//	showlist(&newlist);
//	showlist(&head);

		//排序
	struct node newsort;
	newsort.next = NULL;
	newsort.next = sort_list(&head, newsort);
	showlist(&newsort);

	destroy(&(head.next));//销毁
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值