用单循环链表存储一个环上的数据,并计算任意两个相邻元素之差是否超过2

#include<iostream.h>

#include<stdlib.h>

 

typedef struct node{

  int  data;

 struct node *next;

}Lnode,*LinkList;

 

//假设下面的单循环链表均为带头结点,而且L指向尾结点。

 

void CreatLinkList(LinkList &L)

{//建立一个单循环链表L,数据为整数,数据由键盘随机输入。

 int i;

 LinkList head;

 L=(LinkList)malloc(sizeof(struct node));

 L->next=L;

 head=L;

 cout<<"please input the data of the node "<<endl

  <<"input 0 means end :";

 cin>>i;

 while(i)

 {

  LinkList p=(LinkList)malloc(sizeof(struct node));

  if(!p)

  {

   cout<<"alloctation error"<<endl;

   exit(1);

  }

  p->data=i;

  L->next=p;

  p->next=head;

  L=p;

  cout<<"please input the data of the node "<<endl

  <<"input 0 means end :";

  cin>>i;

 }

}

 

void PrintLinkList(LinkList L)

{//输出单循环链表L的数据元素。

 LinkList temp=L->next;

 cout<<"The List Is :"<<endl;

 while(temp->next!=L->next)

 {

  cout<<temp->next->data<<endl;

  temp=temp->next;

 }

}

int LinkListLengh(LinkList L)

{//计算单循环链表L的数据元素个数。

 int i=0;

 LinkList temp=L->next;

 while(temp->next!=L->next)

 {

  i++;

  temp=temp->next;

 }

 return i;

}

void CalculateLinkList(LinkList L, int i)

{int a,b,k=0;

if((i>LinkListLengh(L)) || (i<1) )

 {

  cout<<"输入错误!"<<endl;

  return ;

 }

 LinkList temp=L->next;

 while((temp!=L) && (k<i))

 {

  k++;

  temp=temp->next;

 }

a=temp->data;

b=temp->next->data;

cout<<a<<"-"<<b<<"="<<a-b<<endl;

if((a-b)>=-2&&(a-b)<=2) cout<<"从第"<<i<<"位开始的相临的两个元素的绝对值不超过2!"<<endl;

else cout<<"从第"<<i<<"位开始的相临的两个元素的绝对值超过2!"<<endl;

}

void main()

{//调用上面的各函数,运行并检验程序是否正确。

 LinkList L;

 int i;

 CreatLinkList(L);

 PrintLinkList(L);

 cout<<"链表长度为:"<<LinkListLengh(L)<<endl;

 cout<<"输入要计算的数字位数:"<<endl;

 cin>>i;

CalculateLinkList(L, i);

cout<<"结束请按q!"<<endl;

           if(_getch()=='q') cout<<"再见"<<endl;

           else  {while(1);};

}

原文地址:https://www.cnblogs.com/ainima/p/6332089.html