|
-
April 21st, 2009, 04:36 PM
#1
how to trace this code on paper..
i am getting lost with all he variables in each step
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
int explored;
struct node *left;
struct node *right;
struct node *next;
} Node;
void add(Node **ptree, Node *n){
if (*ptree == NULL)
*ptree = n;
else
if (n->value<(*ptree)->value)
add(&(*ptree)->left, n);
else
add(&(*ptree)->right, n);
}
void push(Node **plist, Node *n){
if (n){
n->next = *plist;
*plist = n;
}
}
Node* pop(Node **plist){
Node *n = NULL;
if (*plist){
n = *plist;
*plist = (*plist)->next;
}
return n;
}
void what(Node *tree){
Node *list = NULL;
Node *n;
if (tree){
push(&list, tree);
while (n = pop(&list)){
if (!(n->explored)){
n->explored = 1;
push(&list, n->right);
push(&list, n);
push(&list, n->left);
}
else
printf("%d ", n->value);
}
}
}
Node *create(int num){
Node *n;
n = (Node *)malloc(sizeof(Node));
n->value = num;
n->explored = 0;
n->left = n->right = n->next = NULL;
return n;
}
void main(){
Node *tree = NULL;
add(&tree, create(4));
add(&tree, create(6));
add(&tree, create(5));
add(&tree, create(7));
add(&tree, create(3));
add(&tree, create(2));
add(&tree, create(1));
what(tree);
}
-
April 21st, 2009, 04:51 PM
#2
Re: how to trace this code on paper..
i have already done that by a compiler.
but when i try to do that same process on paper
it gets scrambled and totally wrong.
i dont know in what way to draw each step
so it will work as a compiler
??
Last edited by transgalactic; April 21st, 2009 at 04:54 PM.
-
April 21st, 2009, 05:02 PM
#3
Re: how to trace this code on paper..
why don't you do both using the compiler and on paper at the same time, and see where you went wrong?
-
April 21st, 2009, 05:56 PM
#4
Re: how to trace this code on paper..
Well, that's a rather roundabout way to accomplishing that goal.....kinda clever though. I see what they're doing.
Don't focus on the code, focus on the data structures. Obviously there's a tree and a list, and nodes are being moved between them. If you limit yourself to analyzing that pattern rather than worrying about the low-level details, you should find the problem more tractable.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|