-4
我一直在C++中实现单向链表。但是,我正在努力在特定节点之后插入一个节点,并删除一个有目标的节点。我检查了解析到节点的节点,并发现节点甚至没有附加到链表中。节点不附加到链接列表
struct SNode {
string* element;
SNode *next; // Pointer to the next node
/* Creates a node. */
SNode(string* e, SNode* n) {
element = e;
next = n;
}
string* getElement() { return element; }
void print() { cout << *element; }
};
class SList {
protected: // data member
SNode* head;
long size; // number of nodes in the list
public:
/* Default constructor that creates an empty list */
SList() {
head = NULL;
size = 0;
}
// ... update and search methods would go here ...
long getSize() { return size; }
int isEmpty() { return size<=0; }
// add a new node to the beginning of the list
SNode* addFirst(string* s) {
SNode* newNode = new SNode(s, head);
head = newNode;
size++;
return newNode;
}
//remove the first node in the list
string* removeFirst() {
if (head==NULL) return NULL;
SNode* node = head;
head = head->next;
string* s = node->element;
node->next = NULL;
delete node->element;
size--;
return s;
}
// insert a new node after node n and store the string s there
void insertAfter (SNode n, string* s) {
SNode* newNode = new SNode(s, n.next);
n.print(); //print out 2
cout << endl;
n.next = newNode;
(n.next)->print(); //print out 6
cout << endl;
((n.next)->next)->print(); //print out 1
cout << endl;
size++;
SNode* iter = head;
while(iter != NULL){
if(iter == &n){
cout << "ok" << endl;
}
iter = iter->next;
} //but not print out "ok"
print();
return;
}
// delete node n and return the string stored in n
string* insertAfter (SNode n) {
SNode* iter = head;
while(iter != NULL){
if(iter->next == &n){
break;
}
iter = iter->next;
}
iter->next = n.next;
n.next = NULL;
string* s = n.element;
delete n.element;
size--;
return s;
}
//display the list's data in order from head to tail
void print() {
SNode* iter = head;
while (iter!=NULL) {
// call SNode method to display iter's data
iter->print();
cout << endl;
iter = iter->next;
}
cout << endl;
}
int isNode(SNode n){
SNode* iter = head;
while(iter != NULL){
if(iter == &n){
return 1;
}
iter = iter->next;
}
return 0;
}
};
int main(void)
{
SList* dl = new SList();
string s1 = "1";
SNode* p = dl->addFirst(&s1);
dl->print();
string s2 = "2";
//dl->addFirst(&s2);
SNode* p2 = dl->addFirst(&s2);
cout << endl;
dl->print();
string s3 = "3";
dl->addFirst(&s3);
dl->print();
string s4 = "4";
dl->addFirst(&s4);
dl->print();
string s5 = "5";
dl->addFirst(&s5);
dl->print();
dl->removeFirst();
dl->print();
dl->removeFirst();
dl->print();
cout << dl->isNode(*p2) << endl; //still not print "ok"
string s6 = "6";
dl->insertAfter((*p2), &s6);
dl->print();
return 0;
}
为什么你是否存储指向'string'的指针而不是复制字符串? – MikeCAT
'insertAfter'中的iter-> next ==&n'将不太可能成为'true'。我建议你应该使用调试器。 – MikeCAT
为什么名为“insertAfter”()的方法显然删除了一个节点? –