关于单向链表插入一个带字符串的结构的问题(大一弱菜求高手指点)

C++语言 码拜 9年前 (2015-11-08) 1024次浏览
原题:已知head指向一个带头结点的单向链表链表中每个节点包含字符型数据和指向本结构结点的指针。编写程序实现在值为
“jone”的结点前插入值为”marit”的结点,若没有值为”jone””的结点,则插在链表最后。
本人的代码
#include <iostream>
#include<string.h>
#include <stdio.h>
using namespace std;
struct ex
{
char *a;  //字符性数据
ex * next;
};
ex *head;
ex *creat()
{
ex *ps;  //节点指针
ex *pEnd;//链尾指针
ps = new ex;
ps->a = new char[64];
gets (ps->a);
pEnd = ps;
while (strcmp(ps->a ,”out”) != 0) //输入out 退出
{
if (head == NULL)
head = ps;
else
pEnd->next = ps;
pEnd=ps;
ps = new ex;
ps->a = new char[64];
gets (ps->a);
}
pEnd->next = NULL;
delete ps;
return head;
}
void showlist(ex*head)
{
cout<<“now the items of list are\n”;
while (head)
{
cout<<head->a<<endl;
head=head->next;
}
}
void insert(ex*head,ex stud)
{
if (head == NULL)
{
head = &stud;
stud.next=NULL;
return;
}
if (strcmp(head->a,”jone”) == 0)
{
stud.next = head->next;
head->next = &stud;
return;
}
ex *pGuard = head;
while (pGuard->next&&strcmp(pGuard->next->a,”jone”)!=0)
{
pGuard = pGuard->next;
}
if (pGuard->next == NULL)
{
pGuard->next = &stud;
stud.next = NULL;
}
else
{
stud.next = pGuard->next;
pGuard->next = &stud;
}
}
int main()
{
head=creat();
showlist(head);
ex c;
c.a=”marit”;
insert(head,c);
showlist(head);
}
在cb 中运行通过,关于单向链表插入一个带字符串的结构的问题(大一弱菜求高手指点)
然而在VC++, 我们老师推荐的编译器 输出是乱码
问下高手本人的代码有什么问题
大一刚学编程几个月,假如有高手指点一下实在太好了, 谢谢大家了。 还
有就是本人申请了堆空间到后来都不知怎么删除了。
假如高手有更好的方法麻烦发一下代码让本人借鉴一下。
解决方案:40分
你这样传的是整个结构的拷贝。在insert中把拷贝插入链中,而不是把main中的ex c插入链中,因此出错。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于单向链表插入一个带字符串的结构的问题(大一弱菜求高手指点)
喜欢 (0)
[1034331897@qq.com]
分享 (0)