微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

《数据结构》一位同学链表程序调试--供大家参考

大家好,下面是一位同学程序的调试修改内容修改内容均用红色注释注明了,好多同学均是发生同样的错误,请大学阅读。

请思考,一定要学会和理解;

希望大家多动调试程序。

#include<iostream>    
using namespace std;    
    
template<class T>    
struct Student    
{    T data;    
    Student<T> * next;    
};    
    
template<class T>    
class LinkList    
{    
public:    
    LinkList();    
    LinkList(T a[],int n);    
    ~LinkList();    
    void Insert(int i,T x);    
    T Delete(int i);    
    void PrintList();    
private:    
    Student<T> * first;    
};    
    
template<class T>    
LinkList<T>::LinkList()    
{   first=new Student<T>;    //增加了 <T>
    first->next=NULL;    
}    
    
template<class T>    
LinkList<T>::LinkList(T a[],int n)    
{    Student<T> *s;                           //增加这一行。
    first=new Student<T>;first->next=NULL;    //增加了 <T>
    for(int i=0;i<n;i++)                                       //增加 int 
    {   s=new Student<T>;s->data=a[i];           // 增加了 <T> 
        s->next=first->next;first->next=s;    
    }    
}    
    // 增加了下面函数
template <class T>  
LinkList<T> :: ~LinkList( )  
{    Student<T> *q;  
    while (first != NULL)          //释放单链表的每一个结点的存储空间  
    {   q = first;                 //暂存被释放结点  
        first = first->next;         // first指向被释放结点的下一个结点  
        delete q;      
    }  
}  

template<class T>    
void LinkList<T>::Insert(int i,T x)    
{    Student<T> *p,*s;                 // 增加了这行代码
     p=first;int count=0;           // 增加 int
    while(p!=NULL&&count<i-1)    
    {   p=p->next;    
        count++;    
    }    
    if(p==NULL)throw"输入错误" ;  // //增加了“ ;   ”
        else{    
        s=new Student<T>;s->data=x;      // 增加了 <T> 
        s->next=p->next;p->next=s;    
    }    
}    
    
template<class T>    
T LinkList<T>::Delete(int i)    
{     Student<T> *p,*q;          ///增加了这行
      T x;
    p=first;int count=0;        //  增加了int
    while(p!=NULL&&count<i-1)    
    {   p=p->next;    
        count++;    
    }    
    if(p==NULL||p->next==NULL)throw"输入错误";   //  增加了;
    else{    
        q=p->next;x=q->data;    
        p->next=q->next;    
        delete q;    
        return x;    
    }    
}    
    
template<class T>    
void LinkList<T>::PrintList()    
{     Student<T> *p;
    p=first->next;    
    while(p!=NULL)    
    {   cout<<p->data<<"  ";    //增加 "  " (不是原来错误,主要为将数隔开)
        p=p->next;    
    }    
cout<<endl;                // 增加了这行 (不是原来错误,主要是将两次输出分行)
}    
    
void main( )      
{    int score[5]={10,20,40,50,60};      
    LinkList<int> scoreList(score,5);    
    scoreList.PrintList();    
    scoreList.Insert(2,30);    
    scoreList.PrintList();    
    scoreList.Delete(4);    
    scoreList.PrintList();    
}    

祝大家程序调试成功!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐