Hello all,
here is the code I came up with for implementing a circular linked list. I get a segmentation fault when I create the list with just one node. With size > 1 circular list works fine! Im not sure but I think it may have something to do with the head pointer pointing to itself.. any ideas?
#include <stdio.h>
using namespace std;
#ifndef CIRCULARLINKEDLIST_H_
#define CIRCULARLINKEDLIST_H_
class Node
{
public:
char* value;
Node* next;
int index;
Node(int in, char* val,Node* nextNode){
index = in;
value = val;
next = nextNode;
}
};
class CircularLinkedList
{
public:
Node* head;
int size;
CircularLinkedList(){
head = NULL;
}
CircularLinkedList(int capacity){
size = capacity;
for (int i = 0; i < capacity; i++)
add(i,NULL); //add new node value of char* NULL
}
void add(int index, char* value)
{
Node* p = head;
if(NULL == head){
head = new Node(index,value,head);
return;
}
if(p->next == NULL){
p->next = new Node(index,value,head);
return;
}
while(p){
if(p->next == head){
p->next = new Node(index,value,head);
return;
}
p = p->next;
}
}
void print()
{
Node *p = head;
while(p){
printf("-> %d ",p->index);
p = p->next;
// if(p == head) return;
}
}
Node* getHead()
{
return head;
}
~CircularLinkedList()
{
Node* p = head;
while(p){
Node* temp = p;
p = p->next;
delete temp;
}
}
};
#endif /*CIRCULARLINKEDLIST_H_*/
main
CircularLinkedList* list = new CircularLinkedList(1);
Node* p = list->getHead();
p = p->next; // seg fault