#include <iostream>
using namespace std;
struct list
{
int data;
struct list *next;
};
typedef struct list node;
node *head;
int count=0;
void insert_node()
{
node *temp=new node();
cout<<"Data: ";
cin>>temp->data;
temp->next=NULL;
count++;
if(head==NULL)
{
head=temp;
}
else
{
node *last=head;
while(last->next != NULL)
{
last=last->next;
}
last->next=temp;
}
}
void print_node()
{
node *temp=head;
if(head==NULL)
{
cout<<"No Data Found";
}
else
{
while(temp!= NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
}
void SumofLAstTwoNodes()
{
node *temp,*t;
int i=0;
int sum=0;
while(count>0)
{
temp=head;
while(temp!=NULL)
{
i++;
if(i==count || i == count-1) ///add only last and last-1 element
{
sum +=temp->data;
}
temp=temp->next;
}
count--;
}
cout<<"
Your Sum: "<<sum<<endl;
return;
}
int main()
{
int flag=1;
while(flag==1)
{
insert_node();
cout<<"Press 1 to Insert Node 0 to Exit: ";
cin>>flag;
}
print_node();
SumofLAstTwoNodes();
return 0;
}
Output
Data: 1
Press 1 to Insert Node 0 to Exit: 1
Data: 4
Press 1 to Insert Node 0 to Exit: 1
Data: 4
Press 1 to Insert Node 0 to Exit: 1
Data: 5
Press 1 to Insert Node 0 to Exit: 0
1 4 4 5
Your Sum: 9
Add your comment