Advertisement
rihardmarius

insertion sort - listas

Dec 8th, 2013
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node {
  5.   int entry = 0; // valores por defecto
  6.   node *next = nullptr;
  7. };
  8.  
  9. struct lista {
  10.     node* root = nullptr;
  11. };
  12.  
  13. void mostrar_lista (lista& l) // funciona
  14. {
  15.     for (node *p = l.root; p != 0; p = p->next)
  16.         cout << p->entry << ' ';
  17.     cout << endl << endl;
  18. }
  19.  
  20. node* create_node (int a)
  21. {
  22.     node* nuevo = new node;
  23.     nuevo->entry = a;
  24.     return nuevo;
  25. }
  26.  
  27. void insertar_nodo_en_orden (lista& l, int a)
  28. {
  29.     node* nuevo = create_node(a);
  30.     node* p = l.root;
  31.     if(l.root == 0)
  32.     {
  33.         l.root = nuevo;
  34.         return;
  35.     }
  36.     if (a <= p->entry)
  37.     {
  38.         nuevo->next = p;
  39.         l.root = nuevo;
  40.         return;
  41.     }
  42.     node* previous = 0;
  43.     while (p != 0 and a > p->entry) //se termina cuando se acaba la lista o encontro un valor menor a a
  44.     {
  45.         previous = p;
  46.         p = p->next;
  47.     }
  48.     nuevo->next = p;
  49.     previous->next = nuevo;
  50. }
  51.  
  52. void insertar_nodo_al_final (lista &l, int a) // funciona
  53. {
  54.     node* nuevo = new node;
  55.     nuevo->entry = a;
  56.     if (l.root != 0) // apunta a algo?
  57.     {
  58.         node* p = l.root;
  59.         while (p->next != 0)
  60.             p = p->next;
  61.         p->next = nuevo;
  62.     }
  63.     else
  64.         l.root = nuevo;
  65. }
  66.  
  67. void insertion_sort (lista& a, lista& b)
  68. {
  69.     node* p = a.root;
  70.     node* q = b.root;
  71.     while (p != 0)
  72.     {
  73.         insertar_nodo_en_orden(b, p->entry);
  74.         p = p->next;
  75.     }
  76. }
  77.  
  78. int main()
  79. {
  80.     lista L, M;
  81.  
  82.     for (int i=6; i>0; i--)  // setea L = 5 4 3 2 1
  83.         insertar_nodo_al_final (L, (i+2)%5);
  84.  
  85.     mostrar_lista(L); // muestra L
  86.  
  87.     insertion_sort(L,M); // crea M ordenado
  88.  
  89.     mostrar_lista(M); // muestra M
  90.  
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement