Mar 4, 2022

Alternate recursive implementation to reverse a list

#include <iostream>
#include <cstdlib>
using namespace std;

class node {
    public:
    int e;
    node* next;
};

void printList(node* r)
{
    while(r)
    {
        cout << "[" << r->e << "]->";
        r = r->next;
    }
    cout << endl;
}

node* buildList()
{
    int size = 5;
    node* prev=NULL;
    node* root;
    node* cur;
    for(int i=0; i<size; i++)
    {
        cur = new node();
        cur->e = rand() % 100;
        if(prev)
        {
            prev->next = cur;
            prev = cur;
        }
        else
        {
            prev = cur;
            root = cur;
        }
    }
    
    cur->next = NULL;
    
    return root;
}
node* reverseList(node* r, node** newRoot)
{
    if(!r->next)
    {
        *newRoot = r;
        return r;
    }
    
    node* last = reverseList(r->next, newRoot);
    //A->1->2->B => A->2->1->B
    //r=1, r->next =2, last=2, last->next=B
    r->next = last->next;
    last->next = r;
    return r;
}

int main() {
// your code goes here
node* root=buildList();
cout<< "before reversing: ";
printList(root);
node* newRoot;
reverseList(root, &newRoot);
cout<< "after reversing: ";
printList(newRoot);
return 0;
}

  ------------------------
  output
  
  before reversing: [83]->[86]->[77]->[15]->[93]->
  after reversing: [93]->[15]->[77]->[86]->[83]->

Mar 2, 2022

Print all permutations of a string

#include <iostream>
#include <cstring>
#include <string>
#define MAXSIZE 256
#define PATSIZE 10
using namespace std;

void permute(char str[], int l, int r)
{
    
    if(l==r)
    {
        cout&lt;&lt; str &lt;&lt; endl;
        return;
    }    
   
    
    for(int i=l;i&lt;=r;i++)
    {
        swap(str[l], str[i]);

        permute(str, l+1, r);
        
        swap(str[l], str[i]);      
    }

}

int main() {
// your code goes here
char txt[] = "abcd";
permute(txt, 0, strlen(txt)-1);
return 0;
}