我想創建單向鏈表(使用類),其中每個列表中將有:指向文本的指針,int數,指向下一個列表的指針。使用類的C++單向鏈表
我需要實現3個功能: 插入(這將插入一個列表到單鏈表和排序根據文本使用strcmp元件,其是通過指針指向) 去除(INT NUM)其去除在其中發生數第一列表。 print()打印整個單鏈表。
我與排除功能的問題,這給誤差在運行時,我有一個猜想是哪裏的問題if (tmp->next == NULL && tmp->number==num) { delete tmp; first = NULL; }
,但我不知道爲什麼會這樣。
而且我不知道我應該如何實現排序爲插入功能,所以如果你有任何想法,如果你能解釋我在哪裏,我移除了函數的錯誤是,我真的很感激。
下面的代碼:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
class list
{
private:
int number;
char* word;
list* next;
public:
void inserts(int num, char* text);
void removes(int num);
void print();
};
list* first;
void list::print() {
cout <<"This is our list:"<<endl;
// Temp pointer
list *tmp = first;
// No nodes
if (tmp == NULL) {
cout << "EMPTY list" << endl;
return;
}
// One node in the list
if (tmp->next == NULL) {
cout <<"NUMBER:\t"<< tmp->number;
cout <<"\tWORD:\t"<< tmp->word << endl;
cout <<"--------------------------------"<<endl;
}
else {
// Parse and print the list
while (tmp != NULL){
cout <<"NUMBER:\t"<< tmp->number;
cout <<"\tWORD:\t"<< tmp->word << endl;
cout <<"--------------------------------"<<endl;
tmp = tmp->next;
}
}
}
void list::inserts(int num, char* word){
// Create a new list
list* newlist = new list;
newlist->number=num;
newlist->word=word;
newlist->next=NULL;
// Create a temp pointer
list *tmp = first;
if (tmp != NULL) {
// Nodes already present in the list
// Parse to end of list
while (tmp->next != NULL) {
tmp = tmp->next;
}
// Point the last node to the new node
tmp->next=newlist;
}
else {
// First node in the list
first = newlist;
}
}
void list::removes(int num){
int k = 0;
list* tmp=first;
if(tmp==NULL)
return;
//Last node of the list
if (tmp->next == NULL && tmp->number==num) {
delete tmp;
first = NULL;
}
else {
//Parse thru the nodes
list* prev;
prev = new list;
while (tmp != NULL)
{
if (tmp->number == num && k == 0)
first = first->next;
if (tmp->number == num)
break;
prev = tmp;
tmp = tmp->next;
k++;
}
//Adjust the pointers
prev->next=(tmp->next);
//Delete the current node
delete tmp;
delete prev;
}
}
int main()
{
first->print();
first->inserts(1200,"endian");
first->print();
/* first->inserts(10,"endianness");
first->inserts(1200,"PEEK");
first->inserts(1200,"POKE");
first->inserts(1200,".MIL");
first->print();*/
first->removes(100);
first->print();
getchar();
}
「指針到文本」 ***爲什麼?***只有在合理不使用'的std :: string'非常具體cicumstances,並沒有任何的好處,你的情況'字符*'複雜的事情。 – leftaroundabout 2012-03-14 19:55:53
顯然,在STL之後的15年裏,C++被教授char *。壓抑。 – JohnMcG 2012-04-27 15:22:14