[ create a new paste ] login | about

Link: http://codepad.org/NpLBsdYO    [ raw code | output | fork ]

C++, pasted on Oct 28:
#include <ostream>




template<typename T>
class tlist {

     struct node {
         T     data;
         node* next;
     };

private:
     node* head;
     node* tail;
public:
     tlist(void): head(NULL), tail(NULL){}
     ~tlist() {
          this->clear();
     }
public:

     // добавление в хвост
     void add(const T& data) {
          node* n = new node();
          n->data = data;
          n->next = NULL; 
          if(head == NULL)
               head = tail = n;
          else {
               tail->next = n;
               tail       = n;
         }
     }

     // слияние
     void merge(const tlist& l1, const tlist& l2) {
          this->clear();
          const node* p1 = l1.head, *p2 = l2.head;

          while((p1 != NULL) || (p2 != NULL)) {
               if(p1 != NULL) {
                     if((p2 == NULL) || (p1->data <= p2->data)) {
                           this->add(p1->data);
                           p1 = p1->next;
                     }
               }

               if(p2 != NULL) {
                     if((p1 == NULL) || (p2->data <= p1->data)) {
                           this->add(p2->data);
                           p2 = p2->next;
                     }
               }
          }
    }

    // печать
    void print(std::ostream& hout) {
         for(const node* p = head; p != NULL; p = p->next)
               hout << p->data << ' ';
         hout << std::endl;
    }

    // чистка
    void clear(void) {
         node* tmp;
         while(head != NULL) {
               tmp  = head;
               head = head->next;
               delete tmp;
         }
         tail = NULL;
    }
};






int main(void){
      tlist<float> l1, l2, l3;

      for(int i = 0; i < 10; i++) {
          l1.add((float)i*2.0f);
          l2.add((float)i*2.0f + 1.0f);
      }
      l1.print(std::cout);
      l2.print(std::cout);

      l3.merge(l1, l2);
      l3.print(std::cout);
      return 0;
}


Output:
1
2
3
0 2 4 6 8 10 12 14 16 18 
1 3 5 7 9 11 13 15 17 19 
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 


Create a new paste based on this one


Comments: