C++ Programming - Split Linked List into Two

Given a linked list



We have to split it into two. One of the obvious way is to traverse the linked list once get the count and terminating at the midpoint. But it will be of the order n + n/2. Another solution is to add intermediate elements into another linked list which will be of the order n.




Here is the solution (C++):



template class node {
T val;
node *nxt;
public:
node(T v): val(v), nxt(NULL) {}
node(T v, node *n): val(v), nxt(n) {}

T& operator()()
{
return val;
}

node *next()
{
return nxt;
}

void next(node *n)
{
nxt = n;
}

T& operator==(T v)
{
val = v;
}
};

template class Util
{
public:
static node *insert(node **begin, int value)
{
node *me = new node(value);

if ( (me == NULL) || (begin == NULL))
return me;

if ( *begin == NULL )
*begin = me;
else
last(*begin)->next(me);

return me;
}

static bool remove(node **begin, int value)
{
if ( (begin == NULL) || (*begin == NULL))
return false;

node *me = *begin, *prev = NULL;

while(me) {
if ( (*me)() == value )
break;
prev = me;
me = me->next();

}

if ( *begin == me )
*begin = me->next();

if ( prev && me )
prev->next(me->next());

delete me;

return (me != NULL);
}

static node find(node *me, int value)
{
while(me) {
if ( (*me)() == value )
break;
me = me->next();
}
return me;
}

static node *split(node *me)
{
if ( (me == NULL) || (me->next() == NULL))
return NULL;

node *nme = me->next();

node *sec = nme;

while(nme) {
me->next(nme->next());

me = nme;
nme = nme->next();
}

return sec;
}

static void print(node *me)
{
while(me) {
std::cout << (*me)();
me = me->next();
if ( me ) std::cout << " -> ";
}
std::cout << "--|" << std::endl;
}

static node* last(node *begin)
{
node *theone = NULL;
if (begin == NULL) return theone;

theone = begin;
while(theone->next() != NULL)
{
theone = theone->next();
}

return theone;
}
};

int main()
{
node *first = NULL;
int input[] = { 1,2,3,4,5,6,7};

for(int i = 0 ; i < sizeof(input)/sizeof(input[0]); ++i)
Util::insert(&first,input[i]);

std::cout << "Input: " << std::endl;
Util::print(first);

node *second = Util::split(first);

std::cout << "Output: " << std::endl;
Util::print(first);
Util::print(second);
}


Labels: ,

Posted by - at 11:02 AM | 2 comments read on

C/C++ Programming - Windows Memory Leak Analysis using DebugDiag

DebugDiag one of the simple tools which has helped me in analyzing memory leaks for Windows. Once we enable the tracker to monitor for memory pressure analysis we can generate memory dumps for corresponding process and do an Analysis to get the stack trace, allocation count and memory leak probability. We can also get the dependent DLL specific memory as well, which helps in narrowing down issue to a module.

Following are the steps which i follow during analysis of a memory leak issue on windows using the debugdiag.


  1. build the binary or module in debug mode

  2. make sure that binary/module PDB file is also generated. Which can be enabled by using /PDB option of link.exe.

  3. deploy the debug binary along with PDB file on the env on which we have to do the analysis

  4. start the process (supposing that this would be a server class program)

  5. start DebugDiag and select the server app to be tracked for "Memory and Handle Leak"

  6. keep doing the operation which results in memory leak for few hours

  7. Under "Processes" tab within DebugDiag right click the server program and select "Create Full Memory Dump"

  8. Then do the analysis using that data file. (How to use the Debug Diagnostics 1.0 tool to analyze a memory dump file)



NOTE: Make sure that the symbol directory configured for DebugDiag points to the folder which contains the necessary PDB files. The folder to search for symbol files can be configured using Tools->Options and Settings->Symbol Search Path For Analysis

Labels: , , ,

Posted by - at 12:15 AM | 0 comments read on

C Programming - Three Beautiful Quicksorts (by Jon Bentley)

This talk describes three of the most beautiful pieces of code that I have ever written: ... all » three different implementations of Hoare's classic Quicksort algorithm. The first implementation is a bare-bones function in about a dozen lines of C. The second implementation starts by instrumenting the first program to measure its run time; a dozen systematic code transformations proceed to make it more and more powerful yet more and more simple, until it finally disappears in a puff of mathematical smoke. It therefore becomes the most beautiful program I never wrote. The third program is an industrial-strength C library Qsort function that I built with Doug McIlroy. A theme running through all three implementations is the power of elegance and simplicity. (This talk expands my Chapter 3 in Beautiful Code, edited by Oram and Wilson and published by O'Reilly in July, 2007.)




Labels:

Posted by - at 2:13 AM | 0 comments read on

C C++ Programming - Useful Tracing and Profiling Tools

I have been searching for few tracing and profiling tools these days. Tracing tools are my fav because we will be able to debug it while it is running and can get an overview of what is happening inside a.out. esp while learning the flow of a prog.

I found the given below tools and links very useful...


Labels: , , , , , ,

Posted by - at 12:02 AM | 1 comments read on

C Programming - Path Correction

If you enter any relative path convert that to absolute path removing those dotdot and dot. Assuming that input is following our grammer :)
eg: Input: /a/b/c/.././ and Output: /a/b

The most obvious solution seems to be stack. But i wanted to give a try with an in-place replacement logic. Here is what i came up with.
Lets start from the other end of the string.

#define COLS 2
#define TESTPATHS{{"/asd/..",""}\
,{"/.",""}\
,{"/a/b/cc/d/..","/a/b/cc"}\
,{"/a/b/cc/d/.","/a/b/cc/d"}\
,{"/a/../cc/.././asd","/asd"}\
,{"/r/../c../dc../.././asd","/c../asd"}\
,{"/a/../c.c/.././asd","/asd"}\
,{"/a/../.c.c/.././asd","/asd"}\
,{"/a/../c..c/.././asd","/asd"}\
,{"/a/../c...c/.././asd","/asd"}\
,{"/a/b/c/d/","/a/b/c/d/"}\
,{"/a/b.c/c/../d/","/a/b.c/d/"}\
,{"",""}\
,{".","."}\
,{"..",".."}\
,{"/a/../c.c/.././rs..","/rs.."}}

int check_skip(char *start, char **cur, char *stop)
{
int retcode = -1;
if (**cur != '.')
retcode = -1;
else if ((*cur + 1 <>= start) && (*(*cur + 1) == '/')
&& (*(*cur - 1) == '/')) {
*cur -= 1;
retcode = 0;
} else if ((*cur - 2 >= start) && (*(*cur + 1) == '/')
&& (*(*cur - 1) == '.') && (*(*cur - 2) == '/')) {
retcode = 1;
*cur -= 2;
}
} else if ((*cur + 1 == stop)) {
if ((*cur - 1 >= start) && (*(*cur - 1) == '/')) {
retcode = 0;
*cur -= 1;
} else if ((*cur - 2 >= start) && (*(*cur - 1) == '.')
&& (*(*cur - 2) == '/')) {
retcode = 1;
*cur -= 2;
}
}
return retcode;
}

char *find_first(const char findme, char *start, char *stop, int oper,
int *pcnt)
{
char *iter = NULL;
if (start == NULL)
return stop;

for (iter = start; iter != (stop + oper); iter += oper) {
if (*iter == findme)
-- * pcnt;
if ((*pcnt == 0) || (*iter == '.'))
break;
}
if (iter == (stop + oper))
iter = stop;
return iter;
}

char *dir_path(char *path)
{
char *dirpath = path;
int dirlen = strlen(path);

char *end = dirpath + dirlen;
char *dest = end;
char *iter = NULL;
int skipcount = 0;

//TODO: skip last slash;

for (iter = end - 1; iter != (dirpath - 1); --iter) {
int rc = check_skip(dirpath, &iter, end);
if (rc != -1) {
skipcount += rc;
continue;
} else {
//skip slash
if ((skipcount != 0) && (*iter != '/')) {
iter = find_first('/', iter, dirpath, -1, &skipcount);
continue;
}
//copy
if ((skipcount == 0) && (iter != dest)) {
*--dest = *iter;
}
}
}
if (skipcount != 0)
printf("parsing error detected\n");
return dest;
}

void test_paths()
{
char *input_strings[][COLS] = TESTPATHS;
int input_size = sizeof(input_strings) / (sizeof(char *) * COLS);

for (int i = 0; i < input_size; i++) {
char *input = strdup(input_strings[i][0]);
char *result = dir_path(input);
if (strcmp(result, input_strings[i][1]) != 0) {
printf
("TEST FAILURE: [ input = %-20s expected = %-20s result = %-20s ]\n",
input_strings[i][0], input_strings[i][1], result);
} else
printf("TEST SUCCESS: [ input = %-40s result = %-20s ]\n",
input_strings[i][0], input_strings[i][1]);
free((void *) input);
}

}

int main(int count, char *args[])
{
if (count != 2) {
printf("usage: %s \n", args[0]);
return -1;
}

char *mypath = strdup(args[1]); //for printing

char *dest = dir_path(mypath);
printf("%-20s : %s\n", "entered path", args[1]);
printf("%-20s : %s\n", "final path", dest);

printf("going to run tests\n");
test_paths();

free((void *) mypath);
return 0;
}


please post your valuable comments and thoughts.

Labels:

Posted by - at 2:41 PM | 0 comments read on

Programming - Code Browsing Made Easy Using ctags+gvim

Using ctags+gvim for code browsing...


The following command generates a tag file for C/C++ ONLY, you can extend the exclude list for more specific one.

ctags -R --languages="-Java,-JavaScript,-HTML,-Perl,-Sh" < directory name >

For listing all supported languages use

ctags --list-languages

Labels: , ,

Posted by - at 6:51 AM | 0 comments read on

C Programming - Removing Loop from a Linked List

Given a Linked List which has loop within it, remove the looping with minimum complexity.

Node:

struct NODE {
int data;
struct NODE *next;
}

Explanation:
If Linked List is as given below

1->2->3->4->5->6
|_________|

What we are doing in this solutions is inserting an element who data element is known to us between every node, such that it looks like

1->B->2->B->3->B->4->B->5->B->6
|__________________|

So the before inserting after the node which is looping we are checking whether that node next to the next is B or not, thereby finding out the looping node.

Solution:


/* Function which removes Loop from LL */

void vRemoveLoop(Node *head1)
{
Node *tmp;
Node *tmp1 = NULL;
for(tmp = head1; tmp!= NULL; tmp = tmp1) {
Node *temp = (Node *) malloc(sizeof(Node));
temp->data = (int) temp;
temp->next = NULL;
if( (tmp->next != tmp) && (tmp->next->next->data != (int) tmp->next->next) )
temp->next = tmp->next;
tmp->next = temp;
tmp1 = temp->next;
}

for(tmp = head1; tmp!= NULL; tmp = tmp->next) {
tmp1 = tmp->next;
tmp->next = tmp->next->next;
if (tmp1->next != NULL )
tmp1->next = tmp1->next->next;
else
tmp1->next = NULL;
}
}


Post in your comments!

Labels:

Posted by - at 11:10 AM | 0 comments read on

C Programming - Divisible By 3 or Not (continued)

Some more additions to my previous post C Programming - Divisible By 3 or Not.

Code:

1. A solution that I got as a comment to my previous post. Thanks Piyush!

struct NODE {
bool returnValue;
struct NODE *next;
} MOD3_LOOP[3];

bool DivBy3(int n)
{
MOD3_LOOP[0].returnValue = TRUE;
MOD3_LOOP[0].next = &MOD3_LOOP[1];

MOD3_LOOP[1].returnValue = FALSE;
MOD3_LOOP[1].next = &MOD3_LOOP[2];

MOD3_LOOP[2].returnValue = FALSE;
MOD3_LOOP[2].next = &MOD3_LOOP[0];

NODE *iterator = &MOD3_LOOP[0];
int val = n;

while(val != 0) {
for (int i = 0; i < (val & 0x03); i++)
iter = iter->next;
val = val>>2;
}

return (iter->returnValue);
}


2. Another One

int div3(int number)
{
if ( number < 0 ) number = -number;
while ( number > 2 ) {
unsigned int odd = number & 0xaaaaaaaa;
unsigned int even = number & 0x55555555;
int count = 0;
while(odd) {
odd &= (odd-1);
count++;
}
while(even) {
even &= (even-1);
count--;
}
if ( count < 0 ) count = -count;
number = count;
}
return (number == 0);
}


Please post in your comments about these solutions.

Labels:

Posted by - at 10:14 AM | 0 comments read on

C Programming - Copy Linked List (including arbitrary pointer)

Given a Linked List of node structure as

struct Node {
type element;
Node *next;
Node *arb;
};

You are asked to create an exact copy this linked list. Pointer arb points to an arbitrary node with in the Linked List.

Solution:

Suppose the original linked list is like
X1->X2->X3->....->NULL we are supposed to create another Linked List like Y1->Y2->Y3->....->NULL.
First we modify the Source Linked list to look like
X1->Y1->X2->Y2->X3->Y3->.....->NULL, during which we only copy the data element. In another loop we obtain the value of arb by considering the fact the Xn's arb's next will be Yn's arb. Then we reverse back the Source Linked list along with destination linked list to the orginal structure.

Code:

#include < iostream >
#define ARRAY 2,1,3,4,2,3,4,5,6,7,1
using namespace std;

typedef struct NODE {
int data;
struct NODE *next;
struct NODE *arb;
} Node;


Node *head1 = NULL;
Node *head2 = NULL;

/* Create a Link List which has to be copied */
void vCreateLL(Node **head)
{
int nArb[] = { ARRAY };
Node *temp = NULL;
int i;

/* Creating LL and filling data element */
for(i = 0; i < sizeof(nArb)/sizeof(nArb[0]); i++ ) {
Node *tmp = (Node *) malloc(sizeof(Node));
tmp->data = rand() % 10;
tmp->arb = NULL;
tmp->next = NULL;
if(*head == NULL ) *head = tmp;
else temp->next = tmp;
temp = tmp;
}

/* Filling up arb with node location given in an array nArb */
temp = *head;
for(i = 0; i < sizeof(nArb)/sizeof(nArb[0]); i++ ) {
Node *tmp = *head;
for(int j = 0; j < nArb[i]; j++ ) {
tmp = tmp->next;
if ( tmp == NULL)
tmp = *head;
}
temp->arb = tmp;
temp = temp->next;
}
}

/* Print the LL along with node pointed by arb */
void vPrintLL(Node *head)
{
for(Node *tmp = head; tmp != NULL; tmp = tmp->next) {
printf("[ %d->%d ] ",tmp->data,tmp->arb->data);
}
printf("\n");
}

/* Copy Function which copies the LL
*which starts with head1 to head2
*/

void vCopyLL(Node *head1,Node**head2)
{
Node *tmp;
Node *tmp1 = NULL;
for(tmp = head1; tmp!= NULL; tmp = tmp1) {
Node *temp = (Node *) malloc(sizeof(Node));
temp->data = tmp->data;
temp->arb = NULL;
temp->next = tmp->next;
tmp->next = temp;
tmp1 = temp->next;
if ( *head2 == NULL )
*head2 = temp;
}

for(tmp = head1; tmp!= NULL; tmp = tmp->next->next)
tmp->next->arb = tmp->arb->next;

for(tmp = head1; tmp!= NULL; tmp = tmp->next) {
tmp1 = tmp->next;
tmp->next = tmp->next->next;
if (tmp1->next != NULL )
tmp1->next = tmp1->next->next;
else
tmp1->next = NULL;
}
}


int main()
{
vCreateLL(&head1);
vPrintLL(head1);

vCopyLL(head1,&head2);
vPrintLL(head2);
return 0;
}

Labels:

Posted by - at 8:59 PM | 1 comments read on

C Programming - Different signature problem with extern variables

One of my friend asked me this question few days back which seemed to be very interesting for me atleast. The question was as follows





File1.c File2.c
1  int arr[80];
 
1 extern int *arr;
2 int main()
3 {
4 arr[1] = 100;
5 return 0;
6 }

What will be the output when complied and linked together?



It was surprising for me to see a segmentation fault for this kind of a code. Even though array and pointers are different in aspects like
1. Array variable is const pointer
2. Array size has to be defined while declaring the variable

Still I thought array will be manipulated like a pointer, but here in this case what is happening is when we are putting the value 100 to arr[1] it taking the value of the pointer here in this case 0 as arr[80] will be filled with zeros and then adding one to that which mean resulting value will be 0x4 as it is a pointer addition. After that it is trying to put 100 into the address pointed by 0x4 which results in a segmentation fault.

I don't have a sincere justification for this other than explaining why it is working like this. If anyone have any response please post it as a comment.

Labels:

Posted by - at 8:18 AM | 3 comments read on

C Programming - Divisible By 3 or Not

Given a number we have to find whether it is divisible by 3 or not without using /,%,*.

We are provided with char *itoa(int) function

Please post in your comments. Let us find a good solution!!!!
Solution:
One of the property of a number divisible by 3 is that its sum of digits will be also divisible by 3.
Suppose abcd is a 4 digit decimal number

abdc = 1000a + 100b + 10c + d = (999a + 99b + 9c) + (a + b + c + d)

Here the
999a + 99b + 99c
is divisible by 3. So if
a + b + c + d
is also divisible by three then the number is divisible by three.

Functions:

The most obvious one is

/* returns the remainder */
int mod3(unsigned number)
{
while (number > 3 ) { number -= 3; }

number = number == 3 ? 0 : number;
return number;
}

The same thing modified in a bitwise form will be

int mod3(unsigned number)
{
const unsigned int s = 2;
const unsigned int d = (1 << s) - 1;
unsigned int modulus;

for (modulus = number; number > d; number = modulus) {
for (modulus = 0; number; number >>= s) {
modulus += number & d;
}
}
modulus = modulus == d ? 0 : modulus;
return modulus;
}

But here are we are provided with atoi so a better solution could be

int mod3(int number)
{
char *iter;
char *str = itoa(number);
while( *(str+1) != '\0' ) {
number = 0; iter = str;
while( *iter != '\0' ) {
number += (*iter - '0');
iter++;
}
str = itoa(number);
}
if ( (*str == '3') || (*str == '6') || (*str == '9') )
return 0;
return 1;
}

The defect with this function is that if not divisible it will always return 1 rather than the modulus.

Labels:

Posted by - at 4:04 AM | 6 comments read on

C Programming - Remove Characters within a String

The characters to be removed from a string is given as another string.

Your comments are valuable!!

Solution:



void remove(char src[], char del[])
{
char hash[26] = {0};
char *fsrc = del,*fdst;
int count;
while(*fsrc) {
hash[*fsrc - 'a'] = 1;
fsrc++;
}
fsrc = fdst = src;
while(*fsrc) {
if ( (*fsrc == ' ') || ( hash[*fsrc - 'a'] == 0 ) ) {
*fdst = *fsrc;
fdst++;
}
fsrc++;
}
*fdst = '\0';
}

Labels:

Posted by - at 10:59 PM | 0 comments read on

C Programming - Rev()

An array of size N has distinct values 1…N in random order. You have only operator called rev(X) (where X is any value from 0 to N-1) which reverses all values from 0 to X (example values 2,3,1,4 and rev(2) gets you 1,3,2,4). Our objective is to sort the array using minimum number of Rev(X) functions. How many permutations of N size array require exactly N number of rev(X) operators to get sorted

a. For size 3 only 1,3,2 requires 3 moves.

This is what I could think off. Do post in your comments!
Solution:


#include < stdio.h >

int elements[] = {1,23,8,3,4,7,8,9,2,1};
int count = sizeof(elements) /sizeof(int);
void rev(int pos)
{
int iter,swaptemp;
for(iter=0; iter < pos/2; iter++) {
swaptemp = elements[iter];
elements[iter] = elements[pos - iter - 1];
elements[pos - iter - 1] = swaptemp;
}
}

int main()
{
int iter,max=0,pos=0,loop=0;
for(iter=0; iter < count; iter++) printf("%d ",elements[iter]); printf("\n");

for(loop=count; loop > 0; loop=pos-1) {
pos=max=0;
for(iter=0;iter < loop;iter++) {
if ( elements[iter] > max ) {
max = elements[iter];
if ( iter > 0 ) {
rev(iter);
if ( elements[iter+1] < elements[iter] ) {
printf("Swapping %d\n",elements[iter+1]);
rev(iter+1);
}
else
continue;
}
}
pos++;
}
rev(pos);
}

for(iter=0;iter < count;iter++) printf("%d ",elements[iter]); printf("\n");
}

Labels:

Posted by - at 10:32 PM | 0 comments read on

C Programming - String to Integer (atoi)

Another TechMahindra Interview question. The question was to convert a VALID string into its corresponding integer value.

Post in your comments!

Solution:


int atoi(char *string)
{
int value=0,sign=1;

if ( !string || !*string ) return 0;

if ( *string == '-' ) {
sign = -1;
string++;
}

while ( *string ) {
if ( (*string >= '0') && (*string <= '9') ) {
value = value * 10 + (*string - '0');
}
else
break;
string++;
}
return sign * value;

}

Labels:

Posted by - at 9:36 PM | 1 comments read on

C Programming - Reverse Bits in an Integer

It is supposed to be an 32bit integer.

Solution:


unsigned int
reverse(register unsigned int x)
{
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
return((x >> 16) | (x << 16));

}

Labels:

Posted by - at 7:05 AM | 0 comments read on

C Programming - Remove Concequetive Repeting Chars with that Character

What I meant was convert "aaabccddd" to "abcd".

Solution:


#include < stdio.h >
#define STRING "aaabccddd"

int replaceCChars(char *string)
{
char *dest=string;

while(*string) {
if ( *string != *(string+1) ) {
*dest++ = *string;
}
string++;
}
*dest = '\0';
}

int main()
{
char a[]=STRING;
printf("Before: %s ",a);
replaceCChars(a);
printf("After: %s\n",a);
}


Labels:

Posted by - at 6:37 AM | 3 comments read on

C Programming - Find Perfect Square Between Two Numbers

TechMahindra Interview Question, this is how I did that.

Solution:


#include < stdio.h >
#define START 10
#define STOP 100
int main()
{
int i=0;
while( (i*i) < START ) i++;
while( (i*i) < STOP ) {
printf("%d ",i*i);
i++;
}
}

Labels:

Posted by - at 6:34 AM | 3 comments read on

C Programming - Reverse Words in a String (In-Place)

Another typical interview question!!

Here is the solution that I could think off...Post your comments!!!

Solution:


#include < stdio.h >
#define SENT "Hello I am Here"

int reverse(char *string, char delimiter)
{
char *src, *dest,*temp=string;
while( *temp ) {
if (*temp == delimiter) {
temp++;
continue;
}
src=dest=temp;
while ( (*(dest+1) != delimiter) && ( *(dest+1) != '\0' ) ) dest++;
temp=dest+1;
while( dest > src ) {
char temp = *dest;
*dest-- = *src;
*src++=temp;
}
}
}


int main()
{
char name[] = SENT;
printf("Before Call: %s\n",name);
reverse(name,'\0'); /* Reverse Complete Sentence */
reverse(name,' '); /* Reverse Words */
printf("After Call: %s\n",name);

}

Labels:

Posted by - at 6:29 AM | 4 comments read on

C Programming - Dynamic Pointer Cast vs Dynamic Reference Cast

Only difference is that in case of bast casts to references a suitable handler can be provided.

Like the one below


try {
A &a = dynamic_cast < A & >(b); // suppose that this fails
}
catch (bad_cast) {
// do what ever you want
}

Labels:

Posted by - at 1:54 AM | 0 comments read on

C Programming - Format Strings are Important!!

Guess, What will be the output?


#include < stdio.h >

int main(int argc, char *argv[])
{
int i=10;
int *j=&i;
printf("aaa%n\n");
printf("%d\n",i);
}



I ran this program on .NET platform with optimization disabled, it should be portable across all other platforms also.

Labels:

Posted by - at 11:44 PM | 3 comments read on

Archives

Links