链表的节点存储单值的情况大概掌握了,如果涉及到结构体的话,参数应该如何设置呢?
想了想,实现了一下,发现本质并没有变化。
#include<iostream>
using namespace std;
struct Student
{
string name;
int score;
};
struct ListNode
{
Student data;
ListNode* next;
};
ListNode* pnewNode(string pname,int pscore)
{
ListNode* newNode = new ListNode;
newNode->data.name = pname;
newNode->data.score = pscore;
newNode->next = NULL;
return newNode;
}
void creatList(ListNode* pHead, string pname, int pscore)//头插法
{
ListNode* newNode = pnewNode(pname, pscore);
newNode->next = pHead->next;
pHead->next = newNode;
}
void tailList(ListNode* pHead, string pname, int pscore)//尾插
{
ListNode* newNode = pnewNode(pname, pscore);
ListNode* pFindplus = pHead;
while (pFindplus->next != NULL)
{
pFindplus = pFindplus->next;
}
pFindplus->next = newNode;
}
void printList(ListNode* pHead)
{
ListNode* pFind = pHead->next;
while (pFind)
{
cout << "姓名: " << pFind->data.name;
cout << " 分数: " << pFind->data.score << endl;
pFind = pFind->next;
}
cout << "查询结束!";
}
int main()
{
ListNode* head = new ListNode;
head->data.name="teacher";
head->data.score = 0;
head->next = NULL;
string a;
cin >> a ;
cout << endl;
int b;
cin >> b;
creatList(head, a, b);
creatList(head, "Jim", 130);
creatList(head, "Jhon", 122);
tailList(head, "NNM", 150);
printList(head);
return 0;
}
巩固了一下头插法和尾插法,中间遇到了一个小插曲
即 本来对姓名 我想设置为 char name [10],
但是发现代入创建新结点函数时,数据域的赋值语句出现了异常,即
ListNode* pnewNode(char pname[ ],int pscore)
{
ListNode* newNode = new ListNode;
newNode->data.name = pname;// 必须是可以修改的左值
newNode->data.score = pscore;
newNode->next = NULL;
return newNode;
}
之前学习遇到过这种情况,但是忘记了。于是又通过去csdn搜了一下。
得出结论: newNode->data.name 是数组名 ,是不可以根据变量来变化的
解决方法:用 string pname代替
(还有说可以用C中的strcpy字符串复制功能)