Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct node2
- {
- void* data;
- struct node2* one;
- struct node2* two;
- };
- struct node1 {
- void* data;
- struct node1* next;
- };
- void prnint(void* p)
- {
- printf("%d ", *(int*)p);
- }
- struct node2* newNode(int data)
- {
- void* p = malloc(sizeof(data));
- *(int*)p = data;
- struct node2* t = (struct node2*)malloc(sizeof(struct node2));
- t->data = p;
- t->one = NULL;
- t->two = NULL;
- return t;
- }
- void printList(struct node2* p)
- {
- static struct node2* root;
- if (root == NULL)
- root = p;
- while (p != NULL)
- {
- prnint(p->data);
- p = p->two;
- if (p == root) // Възлите на списъка започват да се повтарят
- break;
- }
- }
- void display(struct node1** head)
- {
- struct node1* t = *head;
- do {
- prnint(t->data);
- t = t->next;
- } while (t != *head);
- }
- void add1(void* data, struct node1** head)
- {
- struct node1* p = *head;
- if (p == NULL)
- {
- p = (struct node1*)malloc(sizeof(struct node1));
- p->data = data;
- p->next = NULL;
- *head = p;
- return;
- }
- else
- {
- while (p->next)
- p = p->next;
- struct node1* t = (struct node1*)malloc(sizeof(struct node1));
- t->data = data;
- t->next = NULL;
- p->next = t;
- }
- }
- void preorder(struct node2* p, struct node1** listHead)
- {
- if (!p)
- return;
- add1(p->data, listHead);
- preorder(p->one, listHead);
- preorder(p->two, listHead);
- }
- void postorder(struct node2* p, struct node1** listHead)
- {
- if (!p)
- return;
- postorder(p->one, listHead);
- postorder(p->two, listHead);
- add1(p->data, listHead);
- }
- void postorderToLL(struct node2* p, struct node1** listHead)
- {
- postorder(p, listHead);
- struct node1* t = *listHead;
- while (t->next != NULL)
- t = t->next;
- t->next = *listHead;
- }
- void preorderToLL(struct node2* p, struct node1** listHead)
- {
- preorder(p, listHead);
- struct node1* t = *listHead;
- while (t->next != NULL)
- t = t->next;
- t->next = *listHead;
- }
- int main()
- {
- struct node1* listHead = NULL;
- struct node2* root = newNode(2);
- root->one = newNode(4);
- root->two = newNode(19);
- root->one->one = newNode(7);
- root->one->two = newNode(10);
- root->two->one = newNode(22);
- /*
- * 2
- * / \
- * 4 19
- * / \ /
- * 7 10 22
- * prefix - 2 4 7 10 19 22
- * postfix - 7 10 4 22 19 2
- * infix - 7 4 10 2 22 19
- */
- postorderToLL(root, &listHead);
- display(&listHead);
- putchar('\n');
- listHead = NULL;
- preorderToLL(root, &listHead);
- display(&listHead);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement