2013-02-28 3 views
0

Я пытаюсь проверить свой метод удаления в файле LinkedList.ccp. Когда я нахожусь в режиме отладки он укомплектовать удаляет все 4s из списка, но я получаю сообщение:Я получаю STATUS_ACCESS_VIOLATION (C++)

1 [main] trainlinkedlist 9904 exception::handle: Exception: STATUS_ACCESS_VIOLATION 
614 [main] trainlinkedlist 9904 open_stackdumpfile: Dumping stack trace to trainlinkedlist.exe.stackdump 

Любые идеи, что мне нужно сделать, чтобы исправить это?

main.ccp

#include "LinkedList.h" 
#include <iostream>  //ADDED BECAUSE IT IS NEED FOR PROGRAM TO RUN 
#include <cstdlib> 
using namespace std; //ADDED BECAUSE IT IS NEED FOR PROGRAM TO RUN 

/* 
* 
*/ 

int main() { 
    LinkedList Train; 
    srand(time(0)); 
     Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
     Train.InsertAtEnd(4); 
    Train.InsertAtEnd(5); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
    for(int i=0;i<5;i++){ 
     Train.InsertAtEnd((rand()%20)); 
    } 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
     Train.InsertAtEnd(35); 
    Train.InsertAtEnd(2); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
     Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(5); 
    Train.InsertAtEnd(4); 
     Train.InsertAtEnd(4); 
    Train.InsertAtEnd(6); 
    Train.InsertAtEnd(4); 
    Train.InsertAtEnd(4); 
    Train.Delete(4); 
    Train.Display(); 
    return 0; 
} 

LinkedList.h

#ifndef LINKEDLIST_H 
#define LINKEDLIST_H 

typedef int ElementType; 
struct Node { 
    ElementType data; 
    Node * next; 
}; 

class LinkedList 
{ 
public: 
    LinkedList();//create an empty list 
    bool empty(); // return true if the list is empty, otherwise return false 
    void InsertAtEnd(ElementType x);//insert a value x at the end of list 
    void Delete(ElementType x); //if value x is in the list, remove x 
    void Display();// Display the data values in the list 
    private: 
Node * first; //The first node in a Linked list 
}; 

#endif /* LINKEDLIST_H */ 

LinkedList.ccp

#include "LinkedList.h" 
#include <iostream> 
using namespace std; 

/** 
* LinkedList() sets first as a Dummy Node 
*/ 
LinkedList::LinkedList() { 
    first = NULL; 
} 

bool LinkedList::empty() { 
    if (first == NULL) { //when this is true the list is empty 
     return true; 
    } else { 
     return false; //when this is false the list is NOT empty 
    } 
} 

void LinkedList::InsertAtEnd(ElementType x) { 
    Node *p; 
    p = first; 
    if(empty()){ 
     p = new Node; 
     p->data = x; 
     p->next = NULL; 
     first=p; 
     return; 
    } 
    while (p != NULL) { //this while loop looks for the end of the list 
     if (p->next == NULL) { //this is a check for if node p is the last node in the list 
      p->next = new Node; //a new node is created at the end of the list with data value of x and the next is NULL 
      p->next->data = x; 
      p->next->next = NULL; 
      break;  //breaks the while loop when a new node is added 
     } 
     p = p->next; 
    } 
} 

void LinkedList::Delete(ElementType x) { 
    Node *p; //p is used to the find Node that will be deleted 
    Node *q; //q keeps track of the node before the one that is deleted 
    p = first; 
    q = NULL; 
    while(p->data==x){ 
     first=first->next; 
     p->data =0; 
     p->next=NULL; 
     delete p; 
     p=first; 
    } 
    while(p!=NULL){  //this while loop goes through the list 
     if(p->next->data==x){ 
      q=p->next; 
      p->next=p->next->next; 
      q->data=0; 
      q->next=NULL; 
      delete q; 
      q=NULL; 
     }else{ 
      p=p->next; 
     } 
//  if(p->data==x){ //check for the node that needs to be deleted 
//   q->next=p->next; //connects q's next to the p's next 
//   delete p; //deletes the node p points to 
//   p->next= NULL; 
//  } 
//  q=p; 
//  p=p->next; 
    } 
} 

void LinkedList::Display() { 
    Node *p; 
    p = first; 
    while (p != NULL) { 
     if(p->data==-1){  //check used to skip the dummy node 
      p=p->next; 
      continue; 
     } 
     cout << p->data << " "; //prints out all the values in the list 
     p = p->next; 
    } 
} 
+0

предпочтительно использовать имена, как 'is_empty' вместо того, чтобы следовать в заблуждение имен из стандартной библиотеки практика. 'empty' - это глагол. –

+0

для другого аналогичного вопроса. Я разместил короткий [связанный список учебников] (http://stackoverflow.com/questions/14993882/linked-list-and-reading-from-text-file/14994011#14994011) –

+0

'using namespace std , 'НЕ" НЕОБХОДИМО ДЛЯ ПРОГРАММЫ РАБОТЫ ". Поверь мне. –

ответ

0

Вы не делаете достаточно проверки и, вероятно, разыменования NULL указатели.

while(p->data==x) не первый проверить, является ли или нет p 0.

if(p->next->data==x) не первый проверить, является ли или нет p->next 0.

+0

Ответ от Аскер: Это может быть проблема, но я не знаю, как это исправить. Есть идеи? – user2121217

+0

Если вы не понимаете указатели или связанные списки, вы должны сначала понять их, возможно, изучить их и визуализировать. Понимание их - ваш ключ. –

+0

У меня есть базовое понимание того и другого. Я использую только C++ в течение месяца, и я пытаюсь решить это, потому что это назначение через 8 часов. – user2121217

Смежные вопросы