FIFO Queue linked list implementation
Here is code in which I am trying to implement a queue using linked list:
#include <iostream>
#include <cstdlib>
using namespace std;
template <class Item>
class Queue{
public:
struct node{
Item item;node *next;
node (Item x){
item=x; next=0;
}
};
typedef node* link;
link head, tail;
public:
Queue(int){ head=0;}
int empty() const { return head==0; }
void put(Item x){
node* t=tail;
tail=new node(x);
if (head==0) head=tail;
else t->next=tail;
}
Item get(){
Item v=head->item;link t=head->next;
delete head; head=tail return v;
}
};
int main(){
return 0;
}
but I have problems with pointers. For example, when I write Item v = head->
it should show me option to choose item but it does not show. Also in other place of code after -> this sign code does not give me possibili开发者_如何学Cty to choose item or next. Please help.
ON: The -> operator can be overloaded so the development environment cannot be sure what to do with it. You can do the following (temporarily or permanently) if you really want to have auto-completion.
// IMPORTANT. Make sure "head" is not null before you do it!
Node &headNode(*head); // Create a reference
headNode.next = tail; // Use TAB or CTRL+SPACE or whatever here after dot
OFF: I reviewed your code and made some corrections
template <class Item>
class Queue {
public:
Queue()
: head(0)
, tail(0)
{ }
bool empty() const { return head==0; }
void put(const Item& x)
{
Node* t = tail;
tail = new Node(x);
if (head==0)
head = tail;
else
t->next = tail;
}
Item get()
{
Item v = head->item;
Link t = head->next;
delete head;
head = t;
if(head==0)
tail = 0;
return v;
}
private:
struct Node {
Item item;
Node *next;
Node(const Item& x)
: item(x)
, next(0)
{}
};
typedef Node* Link;
Link head,tail;
};
- Removed
int
typed nameless parameter fromQueue
constructor - Renamed
node
toNode
andlink
toLink
becauseItem
isItem
, notitem
. Just to make it somewhat standardized - Initializing
tail
at the constructor ofQueue
. - Using initializer list instead of code where possible.
- Fixing
Queue::get()
, settingtail
to zero if the queue become empty. - Using constant reference in parameter lists of
Queue::put()
andQueue::Node::Node()
Node
,Link
,head
andtail
is private from now.Queue::empty()
returnsbool
instead ofint
from now.
You would probably be better off reusing an existing container.
The STL explicitly contains, for example, a queue
Container Adapter (based on deque
by default, which is the most efficient choice).
If you don't need polymorphic behavior, a std::queue<Item>
is what you're looking for, it's both extremely efficient (more than your custom list-based queue) and you will avoid memory management issues.
If you need polymorphic behavior, then use a std::queue< std::unique_ptr<Item> >
.
精彩评论