Create a sorted singly linked list out of a sorted BST.
list *build_list(node *t, list *curr) {
if(t == 0)
return curr;
curr = build_list(t->left, curr);
curr->next = new list;
curr = curr->next;
curr->d = t->d;
return build_list(t->right, curr);
}
main() {
list head;
tree t;
list *last = build_list(t, &head);
last->next = 0;
// head.next is the head of the new list
}
or
list* foo(tree* root, list* head, list* tail)
{
if(!root) return;
foo(root->left, head,tail);
list* curr=new list();
curr->val=root->val;
if(head==NULL&&tail==NULL)//first node
{
head=tail=curr;
}
else
{
tail->next=curr;
tail=curr;
}
foo(root->right,head,tail);
return head;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment