今天做一个题时想着用链表来处理,由于很少使用指针,之前都是用数组来模拟,导致在实现函数时,虽然在函数中加入新节点时成功,但函数执行结束节点则被销毁,添加失败,再一番搜索查阅后意识到是参数的传递问题,现简单总结归纳,有错还请指正
这个问题想了很久,就是值传递和引用传递的问题,create()函数中的head如果采用值传递的方式,插入新的节点时,改变的只是head所指向的地址,在函数执行过程中,新开辟了一段空间,接着又将head指向新开辟的空间,函数执行结束,空间被销毁,head的值又为空;而如果采用引用传递,插入新节点时改变的则是head所指向地址中存在的内容,即使函数执行结束,由于head是一个全局变量,其写入的新值也不会被销毁
使用指向链表指针的指针
代码实现将一个句子按空格分隔并存入链表中
#include#include using namespace std; struct NODE { string tuple; NODE* next; }*head; void create(NODE** head, string ins) { //将单个词作为节点加入链表 NODE* pnew = new NODE(); pnew->tuple = ins; pnew->next = NULL; if (*head == NULL) *head = pnew; else { NODE* ptmp = *head; while (ptmp->next != NULL) ptmp = ptmp->next; ptmp->next = pnew; } } void div(string t) { //按空格分割 string ch; for (int i = 0; i < t.length(); i++) if (t[i] == ' ') { create(&head, ch); ch = ""; } else ch += t[i]; create(&head, ch); } int main() { string tmp = "This is a test example"; div(tmp); if (head == NULL) cout << "The chain is null!" << endl; else { while (head) { cout << head->tuple << " "; head = head->next; } } return 0; }
结果:
void create(NODE*& head, string ins) {
NODE* pnew = new NODE();
pnew->tuple = ins;
pnew->next = NULL;
if (head == NULL)
head = pnew;
else {
NODE* ptmp = head;
while (ptmp->next != NULL)
ptmp = ptmp->next;
ptmp->next = pnew;
}
}
void div(string t) {
string ch;
for (int i = 0; i < t.length(); i++)
if (t[i] == ' ') {
create(head, ch);
ch = "";
}
else
ch += t[i];
create(head, ch);
}
结果:
void create(NODE* head, string ins) {
NODE* pnew = new NODE();
pnew->tuple = ins;
pnew->next = NULL;
if (head == NULL)
head = pnew;
else {
NODE* ptmp = head;
while (ptmp->next != NULL)
ptmp = ptmp->next;
ptmp->next = pnew;
}
}
void div(string t) {
string ch;
for (int i = 0; i < t.length(); i++)
if (t[i] == ' ') {
create(head, ch);
ch = "";
}
else
ch += t[i];
create(head, ch);
}
执行结果:



