一维数组求和2

#include <iostream>
using namespace std;

#define NUM 100

/*链表数据结构*/
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
/*链表的初始化*/
void InitList(LinkList &L)
{
    L=new LNode;
    L->next=NULL;
}
/*链表数据的插入*/
void InsertList(LinkList &L)//建立循环链表
{
    LNode *head,*temp;
    head=L;
    for(int i=0;i<NUM;i++)
    {
        temp=new LNode;
        temp->data=rand()%2000000000-100000000;
        temp->next=NULL;
        head->next=temp;
        head=head->next;
    }
}
void output(LinkList L)
{
    for(int i=0;i<NUM;i++)
    {
        cout<<L->next->data<<" ";
        L=L->next;
    }
}
int main(int argc, char* argv[])
{
    int max,sum,flag=0;                //sum是子数组的和,max是最大的子数组的和
    int ordern=0,orderx=0;
    LinkList L;
    LNode *temp1,*temp2;
    InitList(L);
    InsertList(L);                    //由用户往链表中插入数据
    temp2=L->next;
    max=L->next->data;                //max初值是链表中第一个数
    for(int j=0;j<NUM;j++,temp2=temp2->next)
    {
        for(int k=j;k<NUM;k++)
        {
            sum=0;
            temp1=temp2;
            for(int h=j;h<=k;h++,temp1=temp1->next)
            {
                 sum=sum+temp1->data;
            }
             if(max<sum)             //将最大值赋给max,并且保存当时的序号 
             {
                 max=sum;
                 ordern=j;
                 orderx=k;
             }
        }
    }
    temp1=L->next;
    cout<<"数组:"<<endl;
    output(L);
    cout<<endl<<"最大子数组是:";
    for(int i=0;i<ordern;i++)         //找出取得最大值的时候的子数组的第一个数
    {
        temp1=temp1->next;
    }
    for(int j=0;j<(orderx-ordern+1);j++,temp1=temp1->next)//将取得最大和的子数组元素输出
    {
        cout<<temp1->data<<"  ";
    }
    cout<<endl<<"最大子数组的和是:"<<max<<endl;;

    return 0;
}

原文地址:https://www.cnblogs.com/lq897897/p/5609895.html