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;
}