求教如何合并两个链表以及释放内存

昼夜勤作息 2012-02-25 10:58:14
 
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define MC (Count *)malloc(sizeof(struct Count));

struct Count
{
int Val;//系数
int Last;//指数
struct Count * pNext;
};


//造链表并赋值
struct Count * Make (void)
{
int val;
int last;
int len;//链表长度
int i;

struct Count * pHead = MC//头指针
if (pHead == NULL)
{
printf("分配内存失败!\n");
exit(-1);
}

struct Count * pList = MC//结点
pList = pHead;
pList->pNext = NULL;

printf("的项数为:");
scanf("%d",&len);

for (i=0;i<len;++i)
{
printf("第%d项为(系数,指数):",i+1);
scanf("%d,%d",&val,&last);

struct Count * pNew = MC
if (pHead == NULL)
{
printf("分配内存失败!\n");
exit(-1);
}

pNew->Val = val;
pNew->Last = last;
pList->pNext = pNew;
pNew->pNext = NULL;
pList = pNew;
}
return pHead;
}

//列出多项式
void List(Count * pHead)
{
struct Count * p = pHead->pNext;
while (p!=NULL)
{
printf("(%dX^%d)",p->Val,p->Last);
p = p->pNext;

if (p!=NULL)
putchar('+');
}
putchar('\n');
return;
}

//多项式相加处理
struct Count * Add (Count * pHead_1,Count * pHead_2)
{
pHead_1 = pHead_1->pNext;

while (pHead_1 != NULL)
{
pHead_1 =pHead_1->pNext;

if (pHead_1->pNext == NULL)
{
pHead_1->pNext = pHead_2;
break;
}
}
return pHead_1;
}

int main (void)
{
struct Count * phead_1 = NULL;
struct Count * phead_2 = NULL;
struct Count * phead_add = NULL;

printf("\n多项式<1>");
phead_1 = Make();
printf("\n你输入的多项式为:\n");
List(phead_1);

printf("\n多项式<2>");
phead_2 = Make();
printf("\n你输入的多项式为:\n");
List(phead_2);

phead_add = Add (phead_1,phead_2);
printf("\n多项式的和为:\n");
List(phead_add);

return 0;
}
/*
在VC++6.0运行结果是:

多项式<1>的项数为:2
第1项为(系数,指数):3,3
第2项为(系数,指数):4,2

你输入的多项式为:
(3X^3)+(4X^2)

多项式<2>的项数为:2
第1项为(系数,指数):2,4
第2项为(系数,指数):5,4

你输入的多项式为:
(2X^4)+(5X^4)

多项式的和为:
(-842150451X^-842150451)+(2X^4)+(5X^4)
Press any key to continue
*/
...全文
177 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
昼夜勤作息 2012-02-26
  • 打赏
  • 举报
回复
表二接表一尾[Quote=引用 1 楼 czh3642210 的回复:]
合并链表要看你怎么合并,是按照什么规则合并
[/Quote]
jixingzhong 2012-02-26
  • 打赏
  • 举报
回复
如果是链表连接,就无需释放,都仍是在使用的。
昼夜勤作息 2012-02-26
  • 打赏
  • 举报
回复
谢谢你[Quote=引用 3 楼 oldm4n 的回复:]
3个问题

1、Add 函数返回的指针不是表1的头节点,而是表1的尾节点(实际上不需要返回,Add函数声明为 void 都行)
2、main函数中,List调用传入的参数应该是phead_1
3、Add 函数中,连接两个链的时候,pHead_1->pNext = pHead_2,实际上是把表2的头节点也链进去了,应该跳过表2的头节点链表2的第一个数据节点:pHead_1->pNext = ……
[/Quote]
oldm4n 2012-02-26
  • 打赏
  • 举报
回复
3个问题

1、Add 函数返回的指针不是表1的头节点,而是表1的尾节点(实际上不需要返回,Add函数声明为 void 都行)
2、main函数中,List调用传入的参数应该是phead_1
3、Add 函数中,连接两个链的时候,pHead_1->pNext = pHead_2,实际上是把表2的头节点也链进去了,应该跳过表2的头节点链表2的第一个数据节点:pHead_1->pNext = pHead_2->pNext
面包大师 2012-02-25
  • 打赏
  • 举报
回复
合并链表要看你怎么合并,是按照什么规则合并

70,021

社区成员

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

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