Advertisement
Denny707

interimento ordinato iterativo

May 27th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct nodo{
  5.     int info;
  6.     nodo *link;
  7. };
  8.  
  9. void addNodoOrdinato(nodo *head,int n) {
  10.     nodo *newNode = new nodo();
  11.     nodo *previous = NULL;
  12.     nodo *current = head;
  13.     while (current != NULL && n > current->info) {
  14.         previous = current;
  15.         current = current->link;
  16.     }
  17.    
  18.     if (previous == NULL) { //Se l'elemento da inserire Γ¨ piΓΉ piccolo della head
  19.         nodo *newNode2 = new nodo(); //creo un nodo
  20.         newNode2->info = head->info; //copio il valore di head in questo nuovo nodo
  21.         head->info = n;    //valorizzo la testa col nuovo valore
  22.         head->link = newNode2; //collego la testa al nuovo nodo
  23.     } else {
  24.         previous->link = newNode;
  25.     }
  26.     newNode->link = current;
  27.     newNode->info = n;
  28. }
  29.  
  30. void display(nodo *head) {
  31.     nodo *list = head;
  32.     while(list->link != NULL) {
  33.         cout << list->info << " ";
  34.         list = list->link;
  35.     }
  36.      cout << list->info << " ";
  37.     cout << endl;
  38. }
  39.  
  40.  
  41. int main(int argc, const char * argv[]) {
  42.     nodo *head2 = new nodo;
  43.     nodo *head= new nodo();
  44.     head2=head;
  45.    
  46.     addNodoOrdinato(head,-9);
  47.     addNodoOrdinato(head,-884);
  48.     addNodoOrdinato(head,4);
  49.     addNodoOrdinato(head,3);
  50.     addNodoOrdinato(head,12);
  51.    
  52.     addNodoOrdinato(head,3);
  53.     display(head2);
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement