2016-08-10 59 views
0

這是我在C++中創建一個單鏈表的代碼。這個鏈表實現有什麼問題?

功能del_alt()刪除從第二元素開始每隔元件。

編譯器沒有提供任何錯誤,但在運行過程中,程序在顯示原始列表後突然終止。

我盡力找到可能的錯誤,但找不到任何。

幫助讚賞。

乾杯。

#include<iostream> 

using namespace std; 
class Node 
{ 
    public: 
     Node() 
     { 
      next=0; 
     } 
     Node *next; 
     int info; 

}; 

class List 
{ 
    private: 
     Node *head,*tail; 
    public: 
     List() 
     { 
      head=0; 
      tail=0; 
     } 
    void del_alt(); 
    void add_to_head(int); 
    void show_list(); 
}; 


void List :: del_alt() 
{ 
    if(!head||(head==tail)) 
    return; 
    else 
    { 
     Node *current,*after,*ptr; 
     for(current=head,after=head->next;current!=0;current=current->next,after=current->next) 
     { 
     ptr=after; 
     current->next==after->next; 
     if(ptr==tail) 
      tail=current; 
     delete ptr; 
     } 
    } 
} 

void List :: add_to_head(int el) 
{ 
    Node *ptr; 
    ptr->info=el; 
    if(!head) 
     { 
      ptr->next=0; 
      head=tail=ptr; 
     } 
    else 
     { 
      ptr->next=head; 
      head=ptr; 
     } 
} 

void List::show_list() 
{ Node *ptr; 
    cout<<"\n\n"; 
    ptr=head; 
    while(ptr!=0) 
    { 
     cout<<"\t"<<ptr->info; 
     ptr=ptr->next; 
    } 
} 
int main() 
{ 
    List l; 
    int el; 
    char ch; 
    cout<<"\n\n\t\t enter elements\n\n\t"; 
    do 
    { 
     cin>>el; 
     l.add_to_head(el); 
     cout<<"\n\t want to enter more ? (y/n) \n"; 
     cin>>ch; 
    }while(ch=='y'||ch=='Y'); 

    cout<<"\n\t Original list -> \n"; 
    l.show_list(); 
    l.del_alt(); 
    cout<<"\n\t After deletion -> \n"; 
    n.show_list(); 
    cout<<"\n\n \\==============================================="; 
} 
+4

請編輯您的問題包含一個[MCVE] – Slava

+0

這也是一個好主意,通過逐行與步進檢查你的代碼調試器在問這裏之前。 –

+0

起初,你的代碼不能編譯。更正後 - 使用調試器 – malchemist

回答

1

問題來自方法add_to_head中的非初始化ptr。

Node *ptr; 
ptr->info=el 

至少PTR應該是一個新的分配單元

Node *ptr = new Node; 
ptr->info=el