Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Центр помощи > [C++ Builder] Списки


Автор: Tsunameh 13.11.2007, 18:10
Доброго времени суток!

Задачка :

Описать функцию , которая проверяет входит ли список L1 в список L2.

Спасибо заранее)

Автор: APM 13.11.2007, 20:29
А что понимается под вхождением списка L1 в L2? 

Автор: Tsunameh 13.11.2007, 20:46
дословно , входят ли элементы списка Л1 в список Л2.

Автор: Tsunameh 14.11.2007, 18:18
Неужели никто не может помочь? 


Извините за "ап" , в правилах неусмотрел..

Автор: APM 14.11.2007, 21:14
Ты в начале попробуй сам что-нибудь написать, а там глядишь и помогут. Задачка то простая. Создаем два списка, потом каждый элемент из одного списка (L1) ищем в другом списке (L2).

Автор: Tsunameh 14.11.2007, 23:31
Я просто в этом деле профан полный , курс пропустил изза работы ) поэтому сижу локти кусаю =)) 

Автор: Lamak 15.11.2007, 16:32
Код

#include <iostream>
#include <list>

bool L1_in_L2(std::list<int> &L1, std::list<int> &L2)
{
    bool find;
    std::list <int>::iterator itr1;
    std::list <int>::iterator itr2;
    for(itr1=L1.begin();itr1!=L1.end();itr1++) 
    {
        find=false;
        for(itr2=L2.begin();itr2!=L2.end();itr2++) 
        {
            if(*itr2==*itr1)
            {
                find=true;
                break;
            }
        }
        if(!find)
            return false;
    }    
        
    return true;
}

int main()
{
    int i;
    std::list <int>::iterator itr;  
    std::list <int> L1;
    std::list <int> L2;

    L1.insert(L1.end(),8);  
    L1.insert(L1.end(),2);  
    L1.insert(L1.end(),5);  
    for(i=0;i<10;i++)
        L2.insert(L2.end(),i);
    
    std::cout<<"L1=( ";
    for(itr=L1.begin();itr!=L1.end();itr++) 
        std::cout<<*itr<<" ";
    std::cout<<")"<<std::endl;
    std::cout<<"L2=( ";
    for(itr=L2.begin();itr!=L2.end();itr++) 
        std::cout<<*itr<<" ";
    std::cout<<")"<<std::endl;
    
    std::cout<<"L1_in_L2="<< (L1_in_L2(L1,L2)?"true":"false") <<std::endl; 
    
    char ch;
    std::cin>>ch; 
    return 0;
}

Автор: Tsunameh 22.11.2007, 22:22
ламак спасибо! А Можно сделать без подключения библиотеки лист , а через указатель на указатель ? Препод не стал проверять с лист. =(

Автор: Oleg_Ci 24.11.2007, 08:01
Код

#include <iostream>
using namespace std;

////////////////// class //////////////////////////////////////////
template<typename type>
class MyList{
public:
    struct Node{
        Node *Next, *Prev;
        type Value;
        Node( type val = type()): Value(val), Next(NULL), Prev(NULL) {;}
    };
    Node *m_Begin;

    MyList() : m_Begin(NULL){;}
    MyList( const MyList & list );
    template <typename Ty> MyList & operator=( const MyList<Ty> & list );
    void push_front( const type & val ); // всавляем элемент в начало списка
    void Display(); 
    ~MyList();

    //Описать функцию , которая проверяет входит ли список L1 в список L2.
    //входят ли элементы списка Л1 в список Л2.
    template <typename Ty> bool Including( const MyList<Ty> & list );
};
///////////////////// function ///////////////////////////////////
template <typename type> MyList<type>::MyList( const MyList<type> & list ){
    if( list.m_Begin == NULL ){ m_Begin = NULL; return; }
    for( Node * node = list.m_Begin; node != NULL; node = node->Next )
        push_front( node->Value );
}
template <typename type> void MyList<type>::push_front( const type &val ){
    Node * node = new Node( val );
    if( m_Begin == NULL ) m_Begin = node;
    else{
        m_Begin->Prev = node;
        node->Next = m_Begin;
        m_Begin = node;
    }
}
template <typename type> template <typename Ty>
MyList<type> & MyList<type>::operator=( const MyList<Ty> & list ){
    if((void*)this == (void*)&list ) return *this;
    for( MyList<type>::Node * node = m_Begin; node; node = m_Begin->Next ){
        m_Begin = m_Begin->Next;
        delete node;
    }
    m_Begin = NULL;
    for( MyList<Ty>::Node * node = list.m_Begin; node != NULL; node = node->Next )
        push_front(Ty(node->Value));
}    
template <typename type> MyList<type>::~MyList(){
    for( Node * node = m_Begin; node; node = m_Begin ){
        m_Begin = m_Begin->Next;
        delete node;
    }
}
template <typename type> void MyList<type>::Display(){
    for( Node * node = m_Begin; node; node = node->Next )
        cout << node->Value << '\n';
}
//////////
template <typename type> template <typename Ty>
bool MyList<type>::Including( const MyList<Ty> & list ){
    MyList<Ty>::Node * node;
    MyList<type>::Node * mynode;
    for( node = list.m_Begin; node; node = node->Next ){
        for( mynode = m_Begin; mynode; mynode=mynode->Next ){
            if( node->Value == Ty(mynode->Value)) break;
        }
        if(!mynode) return false;
    }
    return true;
}
//////////////////// Main ////////////////////////////////////////
int main(){    
    MyList<int> list;
    list.push_front(5);
    list.push_front(6);
    list.push_front(2);
    list.push_front(1);
    MyList<float> list_f;
    list_f = list;
    //list_f.push_front(34.4);
    list_f.Display();
    cout << "\n";

    if(list.Including(list_f))
        cout << "\n\nOk list1 = list2\n";
    else cout << "\n\nError list1 != list2\n";

    list.Display();
    getchar(); // пауза
    return 0;
}

Автор: Tsunameh 24.11.2007, 16:11
Спасибо огромное! А есть возможность упростить данный код ? До минимума функциональности при работоспособности программы 

Автор: Oleg_Ci 25.11.2007, 08:52
Убрал template
Код

// MS 2005
#include <iostream>
using namespace std;

////////////////// class //////////////////////////////////////////
class MyList{
    typedef int type; // список int'ов
public:
    struct Node{
        Node *Next, *Prev;
        type Value;
        Node( type val = type()): Value(val), Next(NULL), Prev(NULL) {;}
    };
    Node *m_Begin;

    MyList() : m_Begin(NULL){;}
    MyList( const MyList & list );
    MyList & operator=( const MyList & list );
    void push_front( const type & val ); // всавляем элемент в начало списка
    void Display(); 
    ~MyList();

    //Описать функцию , которая проверяет входит ли список L1 в список L2.
    //входят ли элементы списка Л1 в список Л2.
    bool Including( const MyList & list );
};
///////////////////// function ///////////////////////////////////
MyList::MyList( const MyList & list ){
    if( list.m_Begin == NULL ){ m_Begin = NULL; return; }
    for( Node * node = list.m_Begin; node != NULL; node = node->Next )
        push_front( node->Value );
}
void MyList::push_front( const type &val ){
    Node * node = new Node( val );
    if( m_Begin == NULL ) m_Begin = node;
    else{
        m_Begin->Prev = node;
        node->Next = m_Begin;
        m_Begin = node;
    }
}
MyList & MyList::operator=( const MyList & list ){
    if( this == &list ) return *this;
    for( Node * node = m_Begin; node; node = m_Begin->Next ){
        m_Begin = m_Begin->Next;
        delete node;
    }
    m_Begin = NULL;
    for( Node * node = list.m_Begin; node != NULL; node = node->Next )
        push_front(node->Value);
}    
MyList::~MyList(){
    for( Node * node = m_Begin; node; node = m_Begin ){
        m_Begin = m_Begin->Next;
        delete node;
    }
}
void MyList::Display(){
    for( Node * node = m_Begin; node; node = node->Next )
        cout << node->Value << '\n';
}
//////////
bool MyList::Including( const MyList & list ){
    Node * node, * mynode;
    for( node = list.m_Begin; node; node = node->Next ){
        for( mynode = m_Begin; mynode; mynode=mynode->Next ){
            if( node->Value == mynode->Value) break;
        }
        if(!mynode) return false;
    }
    return true;
}
//////////////////// Main ////////////////////////////////////////
int main(){
    MyList list;
    list.push_front(5);
    list.push_front(6);
    list.push_front(2);
    list.push_front(1);
    MyList list_f;
    list_f = list;
    //list_f.push_front(34);
    list_f.Display();
    cout << "\n";

    if(list.Including(list_f))
        cout << "\n\nOk list1 = list2\n";
    else cout << "\n\nError list1 != list2\n";

    list.Display();
    getchar(); // пауза
    return 0;
}

Автор: Chaos A.D. 25.11.2007, 18:37
Ну вы даёте, столько кода для простого поиска...
Код
std::search(...)
 не подойдёт?

Автор: Tsunameh 28.11.2007, 17:17
Хаос , напиши код пжалста - я посмотрю насколько он проще. 

Спасибо за убирание тэмплейт Олег , стало понятнее)

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)