您的位置:首页 > 理论基础 > 数据结构算法

数据结构----单链表(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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: