Thursday, September 17, 2015

Reverse and Block wise reverse of given Linked List

#include <iostream>
using namespace std;
struct node {
int data;
node *next;
};
void create(node *&t,int a)
{
if(t==NULL)
{
t=new node;
t->data=a;
t->next=NULL;
}
else
{
create(t->next,a);
}
}
void rev(node *&t)
{
node *temp=NULL;
node *next;
node *cur=t;
while(t!=NULL)
{
next=t->next;
t->next=temp;
temp=t;
t=next;
}
t=temp;
}
void print(node *t)
{

while(t!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<endl;
}
node *blockrev(node *t,int a)
{
node *next,*cur=t;
node *head;
int flag=0;

node *temp=NULL;
node *curhead=t;
for(int i=0;i<a&&t!=NULL;i++)
{
next=t->next;
t->next=temp;
temp=t;
t=next;
}

if(next!=NULL)
curhead->next=blockrev(next,a);

return temp;
}
int main()
{
int a[]={2,3,4,5,6,7,8,'\0'};
int n=7;
node *t=NULL;
for(int i=0;i<n;i++)
{
create(t,a[i]);
}
print(t);
cout<<"reversing the list\n";
rev(t);
print(t);
rev(t);
cout<<"\nblock wise reverse of list\n";

t=blockrev(t,2);
print(t);
rev(t);
print(t);
return 0;
}

Friday, September 4, 2015

first come first serve Operating system c code

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct process
{
 char name;
 double BT;

}p[5];
int turn=0;
void startnext(int tid)
{
 if(tid==1)
  return;
 tid++;
}
void run(void *tid)
{
 int i=(int )tid;
 while(turn!=i)
 {
  sleep(p[i].BT);
  p[i].BT=0;
  startnext(i);
  pthread_exit(0);
 }
}


int main(int argc,char *argv[])
{
 pthread_t thrs[5];
 int i,j;
 if(argc==6)
 {
  for(i=0;i<5;i++)
  {
   p[i].name=65+i;
   p[i].BT=atoi(argv[i+1]);
  }
 }
 for (int i = 0; i < 5; i++)
 {
  pthread_create(&thrs[i],NULL,&run,(void *)i);
  pthread_join(thrs[i],NULL);
 }
 return 0;
}

Tuesday, September 1, 2015

Add all greater values to every node in a given BST

              50
           /      \
         30        70
        /   \      /  \
     20    40    60   80 

The above tree should be modified to following 

              260
           /      \
         330        150
        /   \       /  \
      350   300    210   80


#include <iostream>
using namespace std;
struct node {
int data;
node *left;
node *right;
};

void addgreater(node *&t,int &sum)
{
if(t==NULL)return ;
if(t)
{
addgreater(t->right,sum);
sum=sum+t->data;
t->data=sum;
addgreater(t->left,sum);
}
}
void create(node *&t,int a)
{
if(t==NULL)
{
t=new node;
t->data=a;
t->left=t->right=NULL;

}
else if(a<t->data)
create(t->left,a);
else
create(t->right,a);

}
void print(node *t)
{
if(t)
{
cout<<t->data<<" ";
print(t->left);
print(t->right);
}
}
int main()
{
int a;
node *t=NULL;

cin>>a;
while(a!=-1){
create(t,a);
cin>>a;
}
print(t);
a=0;
addgreater(t,a);
print(t);

}

Contributors

Translate