Search

воскресенье, 8 апреля 2012 г.

Study day part 3: Links of Nodes

Linklists. Very important part of programing. Not as confusing as multiple Inheritance, but still pretty confusing. What's a linklist? It's a Main Manager Object and many smaller ones (Nodes) that run around. I won't use any full examples cuz' it will take A LOT of lines to do so, but I will provide functions that can be used. So, I guess we should start with declaration:
class List;

class Node{
   int _data;
   Node* _next;  Node* _prev;
   Node(int data, Node* next = (Node*)0);
   friend class List;
};

class List{
   Node* _head;
   Node* _tail;
   Node* _cur;
public:
   List();
   ...(functions)
   virtual ~List();
};
Pretty strait forward. Next. Constructors & Destructor:
Node::Node(int data, Node* next, Node* prev){
   _data = data;
   _next = next;
   _prev = prev; 
   etc...
Queue::Queue(){
   _head = (Node*)0;
}
Queue::~Queue(){
   while(!isEmpty()) removeHead();
}
Now. After we've covered basics, we should move to functions themselves, and we should start with the most basic function possible "isEmpty" because it's used in most methods.
bool Queue::isEmpty(){
   return !_head;
Nature of a linklist is that if there is nothing at the head, there is nothing in the entire list. So we use it here.
After that, we should add something to the head of the list:
void Queue::add(int data){
   if(isEmpty()){
     _head = new Node(data);
   }else{
      Node* cur = _head;
      Node* tail = cur;
      while(cur){
      tail = cur;
      cur= cur->_next;
   }
   tail->_next = new Node(data);
   }
}

int Queue::remove(){
   int ret = _head->_data;
   Node* ToDel = _head;
   _head = _head->_next;
   delete ToDel;
   return ret;
}

This should cover at least most of it.
 

 

Комментариев нет:

Отправить комментарий