这个程序有一点看不懂

flybird66 2003-03-10 09:50:55
/*现有两个带表头节点的单链表la和lb,
此两个表本身无相同元素存在,
la表递增有序,lb表递减有序,
且lb表中的元素包含在la表中连续的某一部分,
设计一个算法找出这部分元素在la的位置,并将它们逆置,使之与lb表中的序相同.*/
#include <iostream.h>
#include <malloc.h>
typedef int elemtype;
typedef struct linknode
{
elemtype data;
struct linknode *next;
}nodetype;

nodetype *create()
{
elemtype d;
nodetype *h=NULL,*s,*t;
int i=1;
cout << "建立一个单链表" << endl;
while (1)
{
cout << " 输入第" << i << "节点data域值:";
cin >> d;
if (d==0) break;

if (i==1)
{
h=(nodetype*)malloc(sizeof(nodetype));
h->data=d;h->next=NULL;t=h;
}
else
{
s=(nodetype *)malloc(sizeof(nodetype));
s->data=d;s->next=NULL;t->next=s;
t=s;
}
i++;
}
return h;
}

void disp(nodetype *h)
{
nodetype *p=h;
cout << "输出一个单链表:" << endl << " ";
if (p==NULL) cout << "空表";
while (p!=NULL)
{
cout << p->data << " ";p=p->next;
}
cout << endl;
}

nodetype *findplace(nodetype *la,nodetype *lb)
{
nodetype *pa,*pb=lb,*ra,*rb=lb;
while(rb->next!=NULL)
rb=rb->next;
pa=la->next;ra=la;
while (pa!=NULL && pa->data!=rb->data)
{
ra=pa;
pa=pa->next;
}
cout << "ra=" << ra->data << endl;
ra->next=lb->next;
pb=lb->next;
while (pa!=NULL && pa->data!=pb->data){
pa=pa->next;
rb->next=pa->next;}
return la->next;
}

void main()
{
nodetype *la,*lb,*lc,*t;
la=create();
lb=create();
disp(la);
disp(lb);
t=(nodetype *)malloc(sizeof(nodetype));
t->next=la,la=t;
t=(nodetype *)malloc(sizeof(nodetype));
t->next=lb;lb=t;
lc=findplace(la,lb);
disp(lc);
}

----------------------------------------------------

ra->next=lb->next;
pb=lb->next;
while (pa!=NULL && pa->data!=pb->data){
pa=pa->next;
rb->next=pa->next;}

这几行我看不懂,lb->next应该是NULL了,怎么ra->next怎么还要等于NULL了?
...全文
24 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
AdenPlus 2003-03-10
  • 打赏
  • 举报
回复
t=(nodetype *)malloc(sizeof(nodetype));
t->next=la,la=t;
t=(nodetype *)malloc(sizeof(nodetype));
t->next=lb;lb=t;
不就等于创建表头节点吗?
yuanhen 2003-03-10
  • 打赏
  • 举报
回复


表头节点是不应该保存数据的, 否则和第一元素节点无二样
yuanhen 2003-03-10
  • 打赏
  • 举报
回复


是带表头的链表吗?在create()中,在进入while(1)循环前
应该有建立头节点的语句,如:
nodetype *p = (nodetype*)malloc(sizeof(nodetype));
p->data = 0;
p->next = NULL;
这样才能算建立好一个头节点啊
langziji 2003-03-10
  • 打赏
  • 举报
回复
楼主给我点分呗
huigll 2003-03-10
  • 打赏
  • 举报
回复
while(rb->next!=NULL)
rb=rb->next;
是rb到了结尾,lb没有动。
flybird66 2003-03-10
  • 打赏
  • 举报
回复
没人愿意帮我吗?
beardxr 2003-03-10
  • 打赏
  • 举报
回复
ra->next=lb->next; //lb->next是b链第一个元素,此句以指向将b链的方法完成倒置,不妥。a链中原有元素没有删除,且新的a链包含b链。
pb=lb->next;
while (pa!=NULL && pa->data!=pb->data){
pa=pa->next; //丢失a链原有的部分元素,内存泄漏。
rb->next=pa->next;}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧