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

简介: #include#include typedef struct node{  int  data; struct node *next;}Lnode,*LinkList; //假设下面的单循环链表均为带头结点,而且L指向尾结点。

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

}

目录
打赏
0
0
0
0
11
分享
相关文章
|
5月前
课时141:链表(数据删除)
1.数据删除的定义 2.在 ILink 接口里面追加新的删除方法 3.后续节点判断 4.完善 LinkImpl 子类中的 remove() 方法
|
5月前
|
课时140:链表(判断数据是否存在)
在一个集合中往往会保存大量的数据,有时候会需要判断数据是否会存在。我们将使用对象比较的方式( Equals 方法)来实现这个功能。
|
5月前
|
课时139:链表(修改指定索引数据)
现在已经可以通过索引来获取链表中的指定数据,既然可以获取数据,那么也就可以实现修改指定索引位置的数据这种常见功能。 本节将介绍如何实现这个功能。
公司监控上网软件架构:基于 C++ 链表算法的数据关联机制探讨
在数字化办公时代,公司监控上网软件成为企业管理网络资源和保障信息安全的关键工具。本文深入剖析C++中的链表数据结构及其在该软件中的应用。链表通过节点存储网络访问记录,具备高效插入、删除操作及节省内存的优势,助力企业实时追踪员工上网行为,提升运营效率并降低安全风险。示例代码展示了如何用C++实现链表记录上网行为,并模拟发送至服务器。链表为公司监控上网软件提供了灵活高效的数据管理方式,但实际开发还需考虑安全性、隐私保护等多方面因素。
87 0
公司监控上网软件架构:基于 C++ 链表算法的数据关联机制探讨
【海贼王的数据航海】链表—双向链表
【海贼王的数据航海】链表—双向链表
61 0
【海贼王的数据航海】链表—单链表
【海贼王的数据航海】链表—单链表
75 0
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
637 0
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
【编织时空三:探究顺序表与链表的数据之旅】(下)
【编织时空三:探究顺序表与链表的数据之旅】
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问