所以我对 C++ 还很陌生,今天我决定坐下来了解链表是如何工作的。到目前为止,我玩得很开心,但是在尝试以相反的顺序打印我的链表时遇到了一个问题(而不是反转链表的顺序!)
另外,我想在没有双链表的情况下做到这一点:
#include <iostream>
#include <string>
using namespace std;
class LinkedList
{
public:
LinkedList()
{
head = NULL;
}
void addItem(string x)
{
if(head == NULL)
{
head = new node();
head->next = NULL;
head->data = x;
} else {
node* temp = head;
while(temp->next != NULL)
temp = temp->next;
node* newNode = new node();
newNode->data = x;
newNode->next = NULL;
temp->next = newNode;
}
}
void printList()
{
node *temp = head;
while(temp->next != NULL)
{
cout << temp->data << endl;
temp = temp->next;
}
cout << temp->data << endl;
}
void addToHead(string x)
{
node *temp = head;
head = new node;
head->next = temp;
head->data = x;
}
int countItems()
{
int count = 1;
for(node* temp = head; temp->next != NULL; temp = temp->next)
++count;
return count;
}
void printReverse()
{
node* temp2;
node* temp = head;
while(temp->next != NULL)
temp = temp->next;
//Print last node before we enter loop
cout << temp->data << endl;
for(double count = countItems() / 2; count != 0; --count)
{
//Set temp2 before temp
temp2 = head;
while(temp2->next != temp)
temp2 = temp2->next;
cout << temp2->data << endl;
//Set temp before temp2
temp = head;
while(temp->next != temp2)
temp = temp->next;
cout << temp->data << endl;
}
cout << "EXIT LOOP" << endl;
}
private:
struct node
{
string data;
node *next;
}
*head;
};
int main()
{
LinkedList names;
names.addItem("This");
names.addItem("is");
names.addItem("a");
names.addItem("test");
names.addItem("sentence");
names.addItem("for");
names.addItem("the");
names.addItem("linked");
names.addItem("list");
names.printList();
cout << endl;
names.addToHead("insert");
names.printList();
cout << endl;
cout << names.countItems() << endl;
cout << "Print reverse: " << endl;
names.printReverse();
cout << endl;
return 0;
}
现在我不确定我的代码崩溃的确切原因,感谢任何帮助!
谢谢!