【数据结构】判断一个单链表中各结点的值是否有序

count记录的是单链表的总长

count1记录的是升序的结点的个数

count2记录的是降序的结点的个数

如果count1或者count2等于count,那么就说明该序列是升序或者降序的。

稍加改进可以在准确判断是升序还是降序还是无序 

(个人认为链表中只有一个结点或者没有结点都是有序的)

#include <stdio.h>
#include <stdlib.h>
typedef struct link_node
{
	int info;
	struct link_node *next;
}N;

N *init()
{
	return NULL;
}

N *creat(N *head)
{
	N *p,*q;
	int x;
	scanf("%d",&x);
	while(x!=-1)
	{
		p=(N*)malloc(sizeof(N));
		p->info=x;
		p->next=NULL;
		if(!head)
		{
			head=p;
			q=p;
		}
		else
		{
			q->next=p;
			q=p;
		}
		scanf("%d",&x);
	}
	return head;
}

void display(N *head)
{
	N *p=head;
	if(head==NULL)
	{
		printf("dispaly  none\n");
		return ;
	}
	while(p)
	{
		printf("%5d",p->info);
		p=p->next;
	}
	printf("\n");
}

int length(N *head)
{
	N *p=head;
	int count=0;
	while(p)
	{
		count++;
		p=p->next;
	}
	return count;
}

int judge(N *head)
{
	int count1=1,count2=1,count=1;
	N *p=head;
	if(!head)
	{
		printf("judge  none\n");
		return 1;
	}
	if(head && !head->next)
	{
		return 1;
	}
	while(p->next)
	{
		if(p->info <= p->next->info)
		{
			count1++;
		}
		if(p->info >=p->next->info)
		{
			count2++;
		}
		p=p->next;
	}
	//count是链表的总长度
	count=length(head);
	printf("count1 = %d\ncount2 = %d\ncount = %d\n",count1,count2,count);
	if(count == count1 || count == count2)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}


int main ()
{
	N *head;
	int count=0;
	head=init();
	head=creat(head);
	display(head);
	if(judge(head))
	{
		printf("有序\n");
	}
	else
	{
		printf("无序\n");
	}
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值