数据结构----单链表(c++)
2017-01-01 16:29
260 查看
题目:输入数据建立节点,并求相邻俩节点data值之和为最大的第一节点,例如:输入:2 6 4 7 3 0(0为结束)
结果:4
程序:
#include <iostream>
using namespace std;
class list
{
private:
int data;
list *next;
public:
list *creat();
void print(list* head_pr);
void adjmax(list* p1);
};
list* head=NULL;
list* list::creat()
{
list *p1,*p2,*s;//p1为第一个结点的指针,p2为当前结点的指针,s为新建结点的指针
p1=NULL;
int input;
cout<<"请输入链表的元素(0 结束输入):";
while(cin>>input)
{
if(input!=0)
{
s=new list;
s->data=input;
}
else
{
break;
}
if(p1==NULL)
{
p1=s;
}
else
{
p2->next=s;
}
p2=s;
}
p2->next=NULL;
head=p1;
return p1;
}
//输出
void list::print(list* head_pr)
{
while(head_pr->next!=NULL)
{
cout<<head_pr->data<<"->";
head_pr=head_pr->next;
}
cout<<head_pr->data;
cout<<endl;
}
// find the max of the sum of the adj two node
void list::adjmax(list* p1)
{
int sum=0;
list* frist;
list* out;
list* biaoji;
while(p1->next!=NULL)
{
biaoji=p1;
p1=p1->next;
if(sum<biaoji->data+p1->data)
{
sum=biaoji->data+p1->data;
out=biaoji;
}
// cout<<sum;
}
cout<<"the max node :"<<out->data;
cout<<endl;
}
int main()
{
list l;
list* main_p=&l;
main_p->creat();
main_p->print(head);
main_p->adjmax(head);
return 0;
}
结果:4
程序:
#include <iostream>
using namespace std;
class list
{
private:
int data;
list *next;
public:
list *creat();
void print(list* head_pr);
void adjmax(list* p1);
};
list* head=NULL;
list* list::creat()
{
list *p1,*p2,*s;//p1为第一个结点的指针,p2为当前结点的指针,s为新建结点的指针
p1=NULL;
int input;
cout<<"请输入链表的元素(0 结束输入):";
while(cin>>input)
{
if(input!=0)
{
s=new list;
s->data=input;
}
else
{
break;
}
if(p1==NULL)
{
p1=s;
}
else
{
p2->next=s;
}
p2=s;
}
p2->next=NULL;
head=p1;
return p1;
}
//输出
void list::print(list* head_pr)
{
while(head_pr->next!=NULL)
{
cout<<head_pr->data<<"->";
head_pr=head_pr->next;
}
cout<<head_pr->data;
cout<<endl;
}
// find the max of the sum of the adj two node
void list::adjmax(list* p1)
{
int sum=0;
list* frist;
list* out;
list* biaoji;
while(p1->next!=NULL)
{
biaoji=p1;
p1=p1->next;
if(sum<biaoji->data+p1->data)
{
sum=biaoji->data+p1->data;
out=biaoji;
}
// cout<<sum;
}
cout<<"the max node :"<<out->data;
cout<<endl;
}
int main()
{
list l;
list* main_p=&l;
main_p->creat();
main_p->print(head);
main_p->adjmax(head);
return 0;
}
相关文章推荐
- (摘)面向对象c++数据结构之基本数据结构-链表-使用链表管理器(连载中)
- C++数据结构------顺序表和链表
- 数据结构 - 有两个链表,第一个升序,第二个降序,合并为一个升序链表(C++)
- C/C++版数据结构之链表<一>
- [c/c++] C数据结构: 链表 Linked List
- 数据结构 链表的lua实现 仿照C++中list 实现
- [C++]数据结构:基于链表结构的Chain类和遍历器ChainIterator类
- C/C++版数据结构之链表<三>
- C/C++版数据结构之链表<二>
- C/C++版数据结构之链表<三>
- 链表的相关操作查找插入删除(c++ 数据结构)
- C++数据结构--链表
- 数据结构学习系类列十-链表集合(c++)
- 数据结构 - 反转单链表(C++)
- 算法与数据结构课程中的c++实现的顺序表和链表
- 《摘》面向对象c++数据结构--基本数据结构之链表-双向链表(结束)(凌风)
- 数据结构学习系列三-单向循环链表(c++实现且应用模板)
- 数据结构_链表_多项式求导_C++实现
- 面向对象c++数据结构--基本数据结构之链表(前篇)(凌风)
- C++类模板 实现双向循环链表的基本算法 《数据结构》(C++版 北京科海)中摘抄