《算法与数据结构》实验课实验三思考题——有序链表插入元素——C语言

#include <stdio.h>
#include <malloc.h>
#define DATATYPE2 char
#define MAXSIZE 100
typedef struct node{
	DATATYPE2 data;
	struct node *next;
}LINKLIST;
int count_head(LINKLIST *head){
	//Single head node list:Output single list element value and count
	int i=0;
	LINKLIST *p;
	p = head->next;
	printf("Output single list's element:");
	while(p != NULL){
		printf(" %c",p->data);
		i++;
		p = p->next;
	}
	printf("\n");
	return i;
}
LINKLIST *creatlink_head_head(LINKLIST *head){
	//use toucharufa built single list with head node
	LINKLIST *t;
	char ch;
	t = (LINKLIST*)malloc(sizeof(LINKLIST));
	head = t;
	t->next = NULL;
	printf("single,lianxu,end with $:");
	while((ch = getchar()) != '$'){
		t = (LINKLIST*)malloc(sizeof(LINKLIST));
		t->data = ch;
		t->next = head->next;
		head->next = t;
	}
	return (head);
}
//sort
LINKLIST sort(LINKLIST *sl){
	LINKLIST *p,*q;
	int temp;
	for(p =sl;p!=NULL;p=p->next){
		for(q = p->next;q != NULL;q = q->next){
			if(p->data>q->data){
				temp = q->data;
				q->data = p->data;
				p->data = temp;
			}
		}
	}
	return (*sl);
}
LINKLIST *insert(LINKLIST *head,char n){
	int c=0;
	LINKLIST*p;
    p=(LINKLIST*)malloc(sizeof(LINKLIST));
	LINKLIST*t;
    t=(LINKLIST*)malloc(sizeof(LINKLIST));
    LINKLIST*r;
    r=(LINKLIST*)malloc(sizeof(LINKLIST));
	p=head->next;
	t=p;
	r=p;
    LINKLIST*s;
	s=(LINKLIST*)malloc(sizeof(LINKLIST));
	while(n>t->data)
	{
		p=p->next;
		t=p->next;
		c++;
	}
	if(c==1)
	{
     s->data=n;
	 s->next=r->next;
	 r->next=s;
	}
	else{
     	s->data=n;
	    s->next=p->next;
        p->next=s;
	}
	return(head);
}
main(){
	LINKLIST *head = NULL;
	int num;
	char n;
	printf("\n   Build single list:\n\n");
	head = creatlink_head_head(head);
	fflush(stdin);
	sort(head);
	printf("Enter the element that you want to insert:");
	scanf("%c",&n);
	insert(head,n);
	num = count_head(head);
	printf("Single list element's number = %d\n",num);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值