链表插入

C++语言 码拜 9年前 (2015-11-08) 1343次浏览
这段代码的功能就是在Jone之前插入marit,可是事实上程序运行起来不是这样子
原题目是在值为“jone”的结点前插入值为”marit“的结点,若没有值为”jone“的结点,则插在链表的最后;
请帮忙看一下本人这个程序错在哪里,谢谢
# include<iostream.h>
struct lianbiao
{
char zifu[10];
lianbiao *next;
};
lianbiao *head;
lianbiao *create()
{
head=NULL;
lianbiao *ps;
ps=new lianbiao;
strcpy(ps->zifu,”jie”);
ps->next=head;
head=ps;
ps=new lianbiao;
strcpy(ps->zifu,”zhao”);
ps->next=head;
head=ps;
ps=new lianbiao;
strcpy(ps->zifu,”chen”);
ps->next=head;
head=ps;
ps=new lianbiao;
strcpy(ps->zifu,”jone”);
ps->next=head;
head=ps;
return (head);
}
void dayin(lianbiao*head)
{
cout<<“插入前的链表为”<<endl;
while(head)
{
cout<<head->zifu<<” “;
head=head->next;
}
cout<<endl;
}
lianbiao *charu(lianbiao*head,lianbiao *insert)
{
int k=1;
lianbiao *p=head;
if(head->zifu==”jone”)
{
insert->next=head;
p=insert;
k=0;
}
while(k)
{
while(head)
{
if(head->next->zifu==”jone”)
{
insert->next=head->next;
head->next=insert->next;
break;
}
if(head->next==NULL)
{
head->next=insert;
insert->next=NULL;
break;
}
head=head->next;
}
k=0;
}
return (p);
}
int main()
{
dayin(create());
lianbiao ps;
strcpy(ps.zifu,”marit”);
dayin(charu(create(),&ps));
return 0;
}
解决方案:25分
#include<iostream>
using namespace std;
struct lianbiao
{
	char zifu[10];
	lianbiao *next;
};
lianbiao *head;
lianbiao *create()
{
	head=NULL;
	lianbiao *ps;
	ps=new lianbiao;
	strcpy(ps->zifu,"jie");
	ps->next=head;
	head=ps;
	ps=new lianbiao;
	strcpy(ps->zifu,"zhao");
	ps->next=head;
	head=ps;
	ps=new lianbiao;
	strcpy(ps->zifu,"chen");
	ps->next=head;
	head=ps;
	ps=new lianbiao;
	strcpy(ps->zifu,"jone");
	ps->next=head;
	head=ps;
	return (head);
}
void dayin(lianbiao*head)
{
	cout<<"插入前的链表为"<<endl;
	while(head)
	{
		cout<<head->zifu<<" ";
		head=head->next;
	}
	cout<<endl;
}
lianbiao *charu(lianbiao*head,lianbiao *insert)
{
	int k=1;
	lianbiao *p=head;
	if(strcmp(head->next->zifu, "jone"))
	{
		insert->next=head;
		p=insert;
		k=0;
	}
	while(k)
	{
		while(head)
		{
			if(head->next == NULL)
			{
				head->next=insert;
				insert->next=NULL;
				break;
			}
			if(strcmp(head->next->zifu, "jone"))
			{
 				insert->next=head->next;
				head->next=insert;//(insert->next)
				break;
			}
			head=head->next;
		}
		k=0;
	}
	return (p);
}
int main()
{
	dayin(create());
	lianbiao ps;
	strcpy(ps.zifu,"marit");
	dayin(charu(create(),&ps));
	system("pause");
	return 0;
}

char 数组和字符串比较最好不用直接用 == 号 用strcmp 和 strncmp比较好

解决方案:5分
本人只想说那是一段乱代码,没有命名规则,没有格式,没有注释,养成良好的习惯,逻辑就没有这么混乱!

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明链表插入
喜欢 (0)
[1034331897@qq.com]
分享 (0)