2 liuyawen44 liuyawen44 于 2015.06.26 23:48 提问

C++链表类前插法与尾插法问题

#include

using namespace std;
class StudentRecord
{
public:
string stuName;
int stuNo;
StudentRecord(string s,int n)
{
stuName=s;
stuNo=n;
}
void print()
{
cout<<"Name:"< }
};
class StudentNode
{
public:
StudentRecord data;
StudentNode *next;
StudentNode(const StudentRecord&stu,StudentNode *pNext=NULL):data(stu),next(pNext) {};
};
class LinkedList
{
public:
StudentNode * head;
StudentNode * tail;
LinkedList():head(0),tail(0) {};
void headinsert(const StudentNode&stu)
{
StudentNode*t=new StudentNode(stu);
t->next=head;
head=t;
}
void headdelete()
{
StudentNode*t=head;
head=head->next;
delete t;
}
void backinsert(const StudentNode&stu)
{
StudentNode*t=new StudentNode(stu);

    if(tail!=0)
        tail->next=t;
    else
        head=t;
    tail=t;

}
void traverse()
{
    StudentNode*t=head;
    while(t!=0)
    {
        t->data.print();
        t=t->next;

    }
}

private:

};
int main()
{
StudentRecord b("td",4),c("sb",4),d("da",4);
LinkedList a;
a.headinsert(d);
a.backinsert(c);

a.traverse();
return 0;

}

这是我写的代码,请看主函数,如何使用了前插法后再用尾插法,我写的代码尾插法总是把前插法覆盖了 !!!!求大神解答,感激不尽!!

2个回答

zhjandcs
zhjandcs   2015.06.27 09:43
已采纳
void headinsert(const StudentNode&stu)
{
    StudentNode*t=new StudentNode(stu);
    t->next=head;
    head=t;
    if(tail == NULL)
        tail = t;
}

liuyawen44
liuyawen44 3Q,大神
2 年多之前 回复
bullzerone
bullzerone   2015.06.27 09:49

感觉尾插法有问题,你插入以后,尾指针没有向后移动,指向最后一个元素
if(tail !=0)
{ tail->next = t;
tail = t->next;}

Csdn user default icon
上传中...
上传图片
插入图片