Saturday 13 August 2016

Check if sum is present in subset of a given array.

#include <iostream>
#define  ll long long int
using namespace std;

int main() {
ll sum,i,req_sum,n,f=0,x;
cin>>n>>req_sum;
ll a[n];
for(i=0;i<n;i++)
cin>>a[i];
x=(1<<n)-1;
for(i=1;i<=x;i++)
{
int b=i;
int j=0;
sum=0;
while(b)
{
int c=b%2;
if(c==1)
{
sum+=a[j];
}
j++;
b=b/2;

}

if(sum==req_sum)
{
f=1;
break;
}

}
if(f==1)
cout<<"Required Sum is Present in Subset of given Set\n";
else
cout<<"Required Sum is not Present in Subset of given Set\n";
// your code goes here
return 0;
}

Friday 12 August 2016

Check if Linked List is a Palindrome in O(n)

#include <iostream>
using namespace std;
struct node {
char data; //can be integer
node * next;
};

void palindrome(node * head)
{

node * p= head;
node *p1=head;
if(head==NULL)
return ;

//Finding middle element
while(p1!=NULL && p1->next!=NULL)
{

p1=p1->next->next;
p=p->next;
}
//Reversing list from middle element
node *curr=p;
node *prev=NULL;
node *next;
while(curr!=NULL)
{
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
p=prev;

//Comparing two halves of Linked List
node *u=p;
node *t=head;
int f=0;
while(u!=NULL)
{

if(u->data!=t->data)
{
f=1;
break;
}
u=u->next;
t=t->next;
}

if(f==1)
cout<<"No\n";
else
cout<<"Yes\n";
}

int main() {
node *start,*p,*p1,*p2,*p3,*p4;
start=new node;
p=new node ;
p1=new node ;
p2=new node ;
p3=new node ;
p4=new node ;
start->data='a';
p->data='b';
p1->data='c';
p2->data='c';
p3->data='b';
p4->data='a';
start->next=p;
p->next=p1;
p1->next=p2;
p2->next=p3;
p3->next=p4;
p4->next=NULL;
palindrome(start);

return 0;
}