链表与结构体联用,关于节点内部赋多值的问题

链表的节点存储单值的情况大概掌握了,如果涉及到结构体的话,参数应该如何设置呢?

想了想,实现了一下,发现本质并没有变化。

#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字符串复制功能)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值