- UID
- 2
- 精华
- 积分
- 7736
- 威望
- 点
- 宅币
- 个
- 贡献
- 次
- 宅之契约
- 份
- 最后登录
- 1970-1-1
- 在线时间
- 小时
|
楼主 |
发表于 2014-7-18 23:49:13
|
显示全部楼层
多项式合并:
- // test.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <stdio.h>
- #include <malloc.h>
- struct ElemType
- {
- ElemType* next;
- float coef;//系数
- int expn;//指数
- };
- ElemType* head1=NULL;
- ElemType* head2=NULL;
- ElemType* CreatePolyn()
- {//初始化多项式
- ElemType* head=(ElemType*)malloc(sizeof(ElemType));
- head->next=NULL;
- return head;
- }
- void AddPolyn(ElemType* head,float coef,int expn)
- {//增加多项式节点
- if(coef == 0.0)
- return;
- for(ElemType* cur=head;cur->next != NULL && cur->next->expn < expn;cur=cur->next);
- ElemType* newnode=(ElemType*)malloc(sizeof(ElemType));
- newnode->next=cur->next;
- newnode->coef=coef;
- newnode->expn=expn;
- cur->next=newnode;
- }
- void PrintPolyn(ElemType* head)
- {//打印多项式
- for(ElemType* cur=head->next;cur != NULL;cur=cur->next)
- {
- printf("coef:%f,expn=%d\n",cur->coef,cur->expn);
- }
- }
- void MergePolyn(ElemType* head1,ElemType* head2)
- {//合并多项式head1+head2->head1
- ElemType* cur1=head1;
- while(cur1->next && head2->next)
- {
- ElemType* cur2=head2->next;
- if(cur2->expn < cur1->next->expn)//插入cur1之前
- {
- head2->next=cur2->next;
- cur2->next=cur1->next;
- cur1->next=cur2;
- }
- else if(cur2->expn == cur1->next->expn)
- {
- cur1->next->coef += cur2->coef;
-
- if(cur1->next->coef == 0)
- {
- ElemType* p=cur1->next;
- cur1->next=p->next;
- delete p;
- }
- else
- {
- cur1=cur1->next;
- }
- head2->next=cur2->next;
- delete cur2;
- }
- else
- {
- cur1=cur1->next;
- }
- }
-
- if(head2->next)
- cur1->next=head2->next;
- head2->next=NULL;
- }
- void DestroyPolyn(ElemType* head)
- {//销毁多项式
- ElemType* cur=head;
- while(cur->next)
- {
- ElemType* p=cur->next;
- delete cur;
- cur=p;
- }
- }
- int main(int argc, char* argv[])
- {
- head1=CreatePolyn();
- head2=CreatePolyn();
- //7+3x+9x^8+5x^17
- AddPolyn(head1,7,0);
- AddPolyn(head1,3,1);
- AddPolyn(head1,9,8);
- AddPolyn(head1,5,17);
- printf("head1:\n");
- PrintPolyn(head1);
- //8x+22x^7-9x^8
- AddPolyn(head2,8,1);
- AddPolyn(head2,22,7);
- AddPolyn(head2,-9,8);
- printf("head2:\n");
- PrintPolyn(head2);
- MergePolyn(head1,head2);
- printf("head1:\n");
- PrintPolyn(head1);
- printf("head2:\n");
- PrintPolyn(head2);
- DestroyPolyn(head1);
- DestroyPolyn(head2);
- getchar();
- return 0;
- }
复制代码
- 单链表头结点移动到链表最后:
- Status A(LinList L)
- {
- if(L && L->next)
- {
- Q=L;
- L=L->next;
- P=L;
- while(P->next) P=P->next;
- P->next=Q;
- Q->next=NULL;
- }
- return OK;
- }
- 双链表拆分成2个双链表
- void BB(LNode* s,LNode* q)
- {
- p=s;
- while(p->next != q)
- p=p->next;
- p->next=s;
- }
- void AA(LNode* pa,LNode* pb)
- {
- BB(pa,pb);
- BB(pb,pa);
- }
- 10进制转换为8进制
- void conversion()
- {
- InitStack(S);
- scanf("%d",N);
- while(N)
- {
- Push(S,N%8);
- N=N/8;
- }
- while(!StackEmpty(s))
- {
- Pop(S,e);
- printf("%d",e);
- }
- }
复制代码 |
|