2013-03-27 3 views
1

인쇄해야하는 C++ 대기열이 있습니다. 첫 번째 노드를 인쇄 한 다음 삭제 한 다음 두 번째 노드 인 첫 번째 노드를 다시 인쇄하면됩니다. 그러나 그것은 단지 한 번 인쇄하기 위해 전체 목록을 지울 것입니다 ... 주위에 해결 방법으로 인쇄 메서드를 전달하고 첫 번째 개체와 같은 일을 임시 큐 개체를 만든이 위대한 포인터를 사용하여 큐를 동적으로 만들 수 있으므로 첫 번째 개체에서 복사 한 개체에서 개체를 삭제하면 여전히 동일한 데이터가 삭제됩니다. 나는 포인터가 아직 좋지 않지만이 작업을 쉽게 수행 할 수있는 방법이 있어야한다고 확신한다.C++의 순회 대기열

int numberPrinted = 0; 
while (!isEmptyQueue()) 
{ 
cout << numberPrinted + 1 << ": " << front() << "\n"; 
deleteQueue();  
numberPrinted++; 
} 

큐 클래스 파일 :

queue2 = queue1; // Temporary queue is assigned values of main queue 
queue2.printQueue(); // Temporary queue is passed to print method 

가 여기 내 인쇄 방법입니다 :

여기 코드의

#ifndef H_linkedQueue 
#define H_linkedQueue 

#include <iostream> 
#include <cassert> 
#include "queueADT.h" 

using namespace std; 

//Definition of the node 
template <class Type> 
struct nodeType 
{ 
    Type info; 
    nodeType<Type> *link; 
}; 


template <class Type> 
class linkedQueueType: public queueADT<Type> 
{ 
public: 
    bool operator== 
        (const linkedQueueType<Type>& otherQueue); 

    bool isEmptyQueue() const; 
     //Function to determine whether the queue is empty. 
     //Postcondition: Returns true if the queue is empty, 
     //    otherwise returns false. 

    bool isFullQueue() const; 
     //Function to determine whether the queue is full. 
     //Postcondition: Returns true if the queue is full, 
     //    otherwise returns false. 

    void initializeQueue(); 
     //Function to initialize the queue to an empty state. 
     //Postcondition: queueFront = NULL; queueRear = NULL 

    Type front() const; 
     //Function to return the first element of the queue. 
     //Precondition: The queue exists and is not empty. 
     //Postcondition: If the queue is empty, the program 
     //    terminates; otherwise, the first 
     //    element of the queue is returned. 

    Type back() const; 
     //Function to return the last element of the queue. 
     //Precondition: The queue exists and is not empty. 
     //Postcondition: If the queue is empty, the program 
     //    terminates; otherwise, the last 
     //    element of the queue is returned. 

    void addQueue(const Type& queueElement); 
     //Function to add queueElement to the queue. 
     //Precondition: The queue exists and is not full. 
     //Postcondition: The queue is changed and queueElement 
     //    is added to the queue. 

    void deleteQueue(); 
     //Function to remove the first element of the queue. 
     //Precondition: The queue exists and is not empty. 
     //Postcondition: The queue is changed and the first 
     //    element is removed from the queue. 
    int numberOfNodes(); 
    // Return number of nodes in the queue. 
    void printQueue(); 
    //Print the queue. 

    linkedQueueType(); 
     //Default constructor 

    linkedQueueType(const linkedQueueType<Type>& otherQueue); 
     //Copy constructor 

    ~linkedQueueType(); 
     //Destructor 

private: 
    nodeType<Type> *queueFront; //pointer to the front of 
           //the queue 
    nodeType<Type> *queueRear; //pointer to the rear of 
           //the queue 
    int count; 
}; 

    //Default constructor 
template<class Type> 
linkedQueueType<Type>::linkedQueueType() 
{ 
    queueFront = NULL; //set front to null 
    queueRear = NULL; //set rear to null 
} //end default constructor 

template<class Type> 
bool linkedQueueType<Type>::isEmptyQueue() const 
{ 
    return(queueFront == NULL); 
} //end 

template<class Type> 
bool linkedQueueType<Type>::isFullQueue() const 
{ 
    return false; 
} //end isFullQueue 

template <class Type> 
void linkedQueueType<Type>::initializeQueue() 
{ 
    nodeType<Type> *temp; 

    while (queueFront!= NULL) //while there are elements left 
           //in the queue 
    { 
     temp = queueFront; //set temp to point to the 
          //current node 
     queueFront = queueFront->link; //advance first to 
             //the next node 
     delete temp; //deallocate memory occupied by temp 
    } 

    queueRear = NULL; //set rear to NULL 
} //end initializeQueue 


template <class Type> 
void linkedQueueType<Type>::addQueue(const Type& newElement) 
{ 
    nodeType<Type> *newNode; 

    newNode = new nodeType<Type>; //create the node 

    newNode->info = newElement; //store the info 
    newNode->link = NULL; //initialize the link field to NULL 

    if (queueFront == NULL) //if initially the queue is empty 
    { 
     queueFront = newNode; 
     queueRear = newNode; 
    } 
    else  //add newNode at the end 
    { 
     queueRear->link = newNode; 
     queueRear = queueRear->link; 
    } 
    count++; 
}//end addQueue 

template <class Type> 
Type linkedQueueType<Type>::front() const 
{ 
    assert(queueFront != NULL); 
    return queueFront->info; 
} //end front 

template <class Type> 
Type linkedQueueType<Type>::back() const 
{ 
    assert(queueRear!= NULL); 
    return queueRear->info; 
} //end back 

template <class Type> 
void linkedQueueType<Type>::deleteQueue() 
{ 
    nodeType<Type> *temp; 

    if (!isEmptyQueue()) 
    { 
     temp = queueFront; //make temp point to the 
          //first node 
     queueFront = queueFront->link; //advance queueFront 

     delete temp; //delete the first node 

     if (queueFront == NULL) //if after deletion the 
           //queue is empty 
      queueRear = NULL; //set queueRear to NULL 
     count--; 
    } 
    else 
     cout << "Cannot remove from an empty queue" << endl; 
}//end deleteQueue 


    //Destructor 
template <class Type> 
linkedQueueType<Type>::~linkedQueueType() 
{ 
    //Write the definition of the destructor 
} //end destructor 

template <class Type> 
bool linkedQueueType<Type>::operator== 
        (const linkedQueueType<Type>& otherQueue) 
{ 
    bool same = false; 

    if (count == otherQueue.count) 
     same = true; 

    return same; 

} //end assignment operator 

    //copy constructor 
template <class Type> 
linkedQueueType<Type>::linkedQueueType 
       (const linkedQueueType<Type>& otherQueue) 
{ 
    //Write the definition of the copy constructor 
}//end copy constructor 
template <class Type> 
int linkedQueueType<Type>::numberOfNodes() 
{ 
    return count; 

} 

template <class Type> 
void linkedQueueType<Type>::printQueue() 
{ 
    int numberPrinted = 0; 
while (!isEmptyQueue()) 
{ 
cout << numberPrinted + 1 << ": " << front() << "\n"; 
deleteQueue();  
numberPrinted++; 
} 
} 
#endif 
+1

표준 대기열 클래스를 사용하는 대기열 클래스입니까? 아니면 직접 작성한 것입니까? 어느 쪽이든, 그것은 어떤 종류의 반복자를 제공합니까? –

+0

표준 대기열 클래스이므로 약간 수정했습니다. 나는 그렇게 믿지 않는다. 수업 파일을 게시 할게 ... – Blake

답변

2

당신의 큐의 printQueue 방법은 이미 큐의 개인 내부에 액세스 할 수 있습니다. 대기열을 인쇄하기 위해 공용 인터페이스를 사용하는 대신 내부 queueFront 포인터를 사용하고 목록을 걸어 각 요소를 인쇄하십시오.

(이 숙제부터 의사)와 같은 뭔가 :이 얼마나 유용 모르지만 당신이 nodeType<Type>.link을 사용하여 다음 각 노드를 연결하기 때문에 다음과 같은 일을 수행 할 수 있습니다

for(node* n = queueFront; n; n = n->next) 
{ 
    // Print data from node n. 
} 
+0

나는 꽤 이해하고 있는지 잘 모르겠다. 혹시 혹시 모범을 보이시겠습니까? – Blake

+0

편집에 대해 너무 고마워, 나는 그걸로 알아낼 수 있다고 생각해. – Blake

+0

"... 대기열의 보호 된 내부 ..."이어야합니다. –

1

당신은 당신이 자신을 쓴 큐 클래스를 사용하는 경우, iterator를 추가하십시오. 이미 반복자가있는 대기열 클래스를 사용하는 경우 반복하여 인쇄하십시오. 반복자가없는 대기열 클래스를 사용하는 경우 다른 대기열 클래스로 전환하십시오.

std::queue을 사용하는 경우 std::list 또는 std::deque으로 전환하십시오.

#include <iostream> 
#include <deque> 

int main() 
{ 
    std::deque<int> mydeque; 

    for (int i=1; i<=5; i++) mydeque.push_back(i); 

    std::cout << "mydeque contains:"; 

    std::deque<int>::iterator it = mydeque.begin(); 

    while (it != mydeque.end()) 
    std::cout << ' ' << *it++; 

    std::cout << '\n'; 
    return 0; 
} 

또는 :

for (std::deque<int>::iterator it = mydeque.begin(); it != mydeque.end(); ++it) 
    // print *it here 
+0

나는 사용하는 클래스가 반복자를 가지고 있다고 생각하지 않는다. 할당을 위해이 클래스 코드를 사용해야한다. (여전히 학교에있다.) 내가 현재 사용하고있는 클래스로 어떻게 할 수 있을까? – Blake

+0

예제를 보여주는 편집을 해 주셔서 고맙습니다. 그걸 봐야 할 지 모르겠군요. – Blake

+0

@Blake :'std :: queue'를 반복 할 수 없습니다. 'std :: queue'를 사용해야한다면, 그것을 반복 할 수 없습니다. –

1

큐가 자신의 코드이며, 내부적 요소를 반복 할 수 있습니다 가정 할 경우

양단을 반복하는 방법을 보여줍니다 cplusplus.coman example있다 , friend ostream& operator<<(ostream&, const your_queue_type&)을주고 출력 스트림에 요소를 쓸 수 있습니다.

class Queue 
{ 
public: 
    // methods 
friend ostream& operator<<(ostream& o, const Queue& q) 
{ 
    // iterate over nodes and stream them to o: o << some_node and so on 
} 
}; 

그런

Queue q = ....; 
std::cout << q << std::endl; // calls your ostream& operator<< 
1

:

int numberPrinted = 1; 
nodeType<Type> *temp; 
if (queueFront != NULL) 
{ 
    temp = queueFront; 
    do 
    { 
     cout << numberPrinted << ": " << temp->info << "\n"; 
     numberPrinted++; 
    }while(temp->link!=NULL); 
} 

이렇게하면 대기열을 변경하지 않고도 포인터를 따라갈 수 있습니다.