Ronzii's Blog

Just your average geek's blog

012 Sort

#include<cstdio>
#include<iostream>
using namespace std;
void sort(int a[], int n)
{
    int low = 0;
    int high = n - 1;
    int mid = 0;
    while(mid <= high)
    {
        switch(a[mid])
        {
        case 0:
            swap(a[low++], a[mid++]);
            break;
        case 1:
            mid++;
            break;
        case 2:
            swap(a[mid], a[high--]);
            break;
        }
    }
}
void printArray(int a[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d ", a[i]);
    }
}
int main()
{
    int a[] = {1, 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1, 2, 1, 0, 2, 2, 2, 1, 1, 0, 0, 2, 1};
    int n = sizeof(a)/sizeof(a[0]);
    sort(a,n);
    printArray(a, n);
    return 0;
}
Advertisements

August 7, 2011 Posted by | C++ | | 2 Comments

Addition of 2 Linked Lists

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
struct node
{
    int value;
    struct node* next;
};
typedef struct node Node;
void push(Node* &front,int n)
{
    Node *temp = (Node*)malloc(sizeof(Node));
    temp->value=n;
    temp->next=NULL;
    if(front==NULL)
    {
        front=temp;
    }
    else
    {
        Node *current = front;
        while(current->next!=NULL)
        {
            current = current->next;
        }
        current->next = temp;
    }
}
void print(Node* ref)
{
    Node *temp;
    temp=ref;
    while(temp!=NULL)
    {
        printf("%d",temp->value);
        temp=temp->next;
    }
}
void reverse(Node* &front)
{
    Node *prev = (Node*)malloc(sizeof(Node));
    Node *current = (Node*)malloc(sizeof(Node));
    Node *next = (Node*)malloc(sizeof(Node));
    current=front;
    prev=NULL;
    while(current!=NULL)
    {
        next=current->next;
        current->next=prev;
        prev = current;
        current = next;
    }
    front=prev;
}
void addLinkedList(Node* a, Node* b)
{
    int carry=0,result=0;
    Node* prev = NULL;
    while(a || b)
    {
        result = carry;
        if(a)
        {
            result+=a->value;
        }
        if(b)
        {
            result+=b->value;
        }
        carry = result/10;
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->value = result%10;
        newNode->next  = prev;
        prev = newNode;
        if(a)
        {
            a = a->next;
        }
        if(b)
        {
            b = b->next;
        }
    }
    while(carry)
    {
        result = carry;
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->value = result%10;
        newNode->next  = prev;
        prev = newNode;
        carry-=result%10;
    }
    print(prev);
}
int main()
{
    Node *a=NULL,*b=NULL;
    push(a,7);
    push(a,4);
    push(a,4);
    push(b,3);
    push(b,1);
    push(b,1);
    push(b,1);
    // Reverse both lists
    reverse(a);
    reverse(b);
    // Add
    addLinkedList(a,b);
    return 0;
}

August 7, 2011 Posted by | C++ | | Leave a comment