Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all articles
Browse latest Browse all 40121

reverse a doubly linked list in a group of given size

$
0
0

can anyone please correct my code because it is not working and i am not able to solve....

 #include<iostream>
 #include<cstdlib>
 #include<algorithm>
 #include<string>
 #include<vector>

 using namespace std;

struct node
{
   int info;
  node *next;
   node *prev;
};

void add(node **start,int data)
{
   struct node *tmp = new node;

  tmp->next = (*start);
  tmp->prev = NULL;
  tmp->info = data;

  if((*start)!=NULL)
  {
    (*start)->prev = tmp;
  }

  (*start) = tmp;
  }

 struct node *reverse_kth(node *start,int k)
 {
   int i=0;

    node *pre=NULL,*curr=(start);
    while(curr!=NULL && i<k-1)
    {
        pre=curr->prev;
        curr->prev=curr->next;
        curr->next=pre;
        curr=curr->prev;
        i++;
    }

    if(curr!=NULL)
    {
        curr->next=reverse_kth(curr->prev,k);
        curr->next->prev=curr;
    }
  return pre->prev;
 }

  void print(node *p)
 {
   while(p!=NULL)
  {
      cout<<p->info<<"<->";
      p=p->next;
  }
   cout<<"NULL\n";
 }

int main()
{
  struct node *a=NULL;

  add(&a,2);
  add(&a,4);
  add(&a,8);
  add(&a,10);

  int k=2;

  cout<<"list before reversing : ";
  print(a);

  a=reverse_kth(a,k);

  cout<<"list after reversing : ";
  print(a);

  return 0;
}

Viewing all articles
Browse latest Browse all 40121

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>