Wednesday, April 11, 2012

Program 11TH in C++

PROBLEM STATEMENT :


input linked list is : 1->9->3->8->5->7->7

do you see any pattern in this input ?

odd placed nodes are in increasing order and even placed nodes are in decreasing order.

write a code that gives the the following linkedlist:

output linked list should be 1->3->5->7->7->8->9

?? can it be done inplace ?



SOLUTION :


#include <iostream.h>
#include <cstdio>
#include <list.h>


using namespace std;


void print(int arr[], int size)
{


list<int> li(arr,arr+size);
list<int> :: iterator it;
list<int> li1;
list<int> :: reverse_iterator it1;
cout<


//storing odd no elements in the new list and deleting the same from old list


for(it=li.begin(); it!=li.end(); it++)
{
li1.push_back(*it);
it=li.erase(it);
if(it!=li.end())
{
continue;
}
else
{
break;
}
}


//old list now contain the even places elements only and adding them from back to front in new list created above


for(it1=li.rbegin(); it1!=li.rend(); )
{
li1.push_back(*it1);
li.remove(*it1);
}


//displaying newly created list


for(it=li1.begin(); it!=li1.end(); it++)
{
cout<<*it<<" ";
}


}


int main()
{


int arr[]={1,9,3,8,5,7,7};
int arr1[]={1,9,4,6,7,3};
int arr2[]={2,5,6,4,9,3};


print(arr,sizeof(arr)/sizeof(int));
print(arr1,sizeof(arr1)/sizeof(int));
print(arr2,sizeof(arr2)/sizeof(int));


}




2 comments:

  1. garima.. the question itself says you are given a linked list... using an array as you have done is actually changing the question iself !

    ReplyDelete
    Replies
    1. I have taken array just to initialize the list..not for processing purpose.
      When list is passed itself array is not needed at all.
      I hope, it makes sense.

      Delete