When I try to use this statement : tail->prev = newElement
;
then entire program just shuts down. I really wonder why.
struct LinkedList{
string var_name;
string scope_name;
int scope; // 0 = global, 1 = public, 2 = private, 3 = ?
LinkedList* next = NULL;
LinkedList* prev = NULL;
};
struct LinkedList* head;
struct LinkedList* tail; //I made this two global
void insert(LinkedList* &head, LinkedList* &newElement, LinkedList* &tail){
newElement->next =NULL;
if(!head){
head = newElement;
return;
}
else{
LinkedList* last = head;
while(last->next != NULL){
last=last->next;
}
last->next = newElement;
newElement->prev = last;
tail = newElement;
tail = newElement->next;
tail->prev = newElement;
}
}
void LexicalAnalyzer:: var_list(){
LinkedList* new_node = new LinkedList[sizeof(LinkedList)];
GetToken();
new_node->var_name = tmp.lexeme;
new_node->scope_name = currentScope;
if(currentScope == "global")
new_node->scope = 0;
else if(pubOrPri == 1)
new_node->scope = 1;
else if(pubOrPri == 2)
new_node->scope = 2;
insert(head, new_node, tail);
//tail->prev = new_node;
display();
if(tmp.token_type == ID){
GetToken();
if(tmp.token_type == COMMA)
var_list();
else if(tmp.token_type == SEMICOLON){
return;
}
else
syntaxError();
}
else
syntaxError();
}
The output gave me
Process returned -1073741819 (0xC0000005) execution time : 3.269 s.
But if I delete tail-> newElement;
and take away the parameter tail in the function. Everything's fine.
And I thought, tail is global then why wouldn't I just directly try tail->prev = new_Node;
in the var_list()
function, didn't work as well.
You don't have any logic to deal with the initial state of tail
, which is nullptr
.
Change
if(!head){
head = newElement;
return;
}
to
if(!head){
head = tail = newElement;
return;
}
In addition, the line
tail->prev = newElement;
needs to be
tail = newElement;
in the else
block.
Disclaimer I haven't tested whether the suggestion fixes the problem.
try this logic,
void insert(LinkedList* &head, LinkedList* &newElement, LinkedList* &tail){
newElement->next =NULL;
if(!head){
head = tail = newElement; // your first node is both head and tail;
return;
}
else{
LinkedList* last = head;
while(last->next != NULL){
last=last->next;
}
last->next = newElement;
newElement->prev = last; // newElement is inserted to end of the list
tail = newElement; // tail is moved to last element in the list
//tail = newElement->next;
newElement->next = NULL; // tail of next is always NULL; end of the list
//tail->prev = newElement;
tail->prev = last; // tail of prev must be last
}
}
User contributions licensed under CC BY-SA 3.0