May 31, 2013 at 1:24pm UTC
i tried implementing Singly Linked List using two classes, SLLNode(node) and SLL(list class)
Here're the implementations
--------SLLink.h-------
#ifndef INT_LINKED_LIST
#define INT_LINKED LIST
class SLLNode
{ public:
int info;
SLLNode *next;
SLLNode(){
info = 0;
}
SLLNode(int infp, SLLNode* testdf = 0){
info = infp;
next = testdf;
}
};
class SLL
{
public:
SLL(){
head = tail = 0;
};
~SLL();
int isEmpty(){
head = tail = 0;
};
void addToHead(int);
void addToTail(int);
int removeFromHead();
int removeFromTail();
private:
SLLNode *head, *tail;
};
#endif
-----------------------------
-----------SLLink.cpp-----------
#include <iostream>
#include "SLLink.h"
SLL::~SLL(){
for ( SLLNode *p; !isEmpty(); ){
p = head->next;
delete head;
head = p;
}
}
void SLL::addToHead(int t){
head = new SLLNode(t,head);
if ( tail == 0)
tail = head;
}
void SLL::addToTail(int t){
if (tail!= 0){
tail->next = new SLLNode(t);
tail = tail->next;}
else head = tail = newSLLNode(t);}
int SLL::removeFromHead(){
int t = head->info;
SLLNode *temp;
temp = head;
if( head == tail)
head = tail = 0;
head = head->next;
delete temp;
return t;
}
int SLL::removeFromTail(){
int t = tail->info;
if(head == tail){
delete head;
head = tail = 0;
}
else{ SLLNode *p = head;
SLLNode *temp;
while( p->next != tail )
p= p-> next;
temp = tail;
tail = p;
delete temp;
tail->next = 0;
/* OR
delete tail; tail = tmp; tail-> next - 0;
*/
}
return t;}
-------------
When i build this i get this error among many others:
'class SLL' has no member named 'next'
Can somebody explain why??
Last edited on May 31, 2013 at 5:20pm UTC
May 31, 2013 at 1:40pm UTC
Your code is invalid. I will not talk about symantic bugs. It is enough to point out syntax bugs. For example what is newSLLNode in statement?
else head = tail = newSLLNode(t);}
As for the error you should point out the statement for which the error was generated.
Last edited on May 31, 2013 at 1:40pm UTC
May 31, 2013 at 1:42pm UTC
SLL and SLLNode are two completely different classes having no relationship at all. the expression head->next does not have any meaning. head belongs to SLL and next belongs to SLLNode.
Also, it will be better if you try to implement linked lists only 1 class instead of two. Careful attention shall have to be paid for memory allocation / de-allocation
May 31, 2013 at 2:15pm UTC
It is obvious that instead of SLL *head, *tail; there shall be SLLNode *head, *tail; in the class definition of SLL.