栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现单向链表-多项式链表表示法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现单向链表-多项式链表表示法

原多项式为:
A=8X^8 + 54X^7 + 7X^6 + 1X^4 + 3X^3 + 4X + 2
B=-2X^9 + 6X^8 + 5X^4 + 6X^3 + 8X^2 + 6X + 9
多项式相加的结果为:
C=-2X^9 + 14X^8 + 54X^7 + 7X^6 + 6X^4 + 9X^3 + 8X^2 + 10X + 11
数组表示法会有以下困扰:
多项式内容变动时,对数组结构的影响相当大,算法处理不易。
由于数组时静态数据结构,所以事先必须查找一块连续的并且够大的内存空间,容易造成内存空间的浪费。
则此时使用单向链表来表示多项式,就可以克服以上的问题。

package linkList;
class Node2{
	int coef;//表示该变量的系数
	int exp;//表示该变量的指数
	Node2 next;//指向下一节点的指针
	public Node2(int coef,int exp) {
		this.coef=coef;
		this.exp=exp;
		this.next=null;
	}
	
}
class PolylinkedList{
	public Node2 first;
	public Node2 last;
	public boolean isEmpty() {
		return first==null;
	}
	public void creat_link(int coef,int exp) {
		Node2 newNode=new Node2(coef,exp);
		if(this.isEmpty()) {
			first=newNode;
			last=newNode;
		}else {
			last.next=newNode;
			last=newNode;
		}
		
	}
	public void print_link() {
		Node2 current=first;
		while(current!=null) {
			if(current.exp==1&¤t.coef!=0) {
				System.out.print(current.coef+"X + ");
			}else if(current.exp!=0&¤t.coef!=0) {
				System.out.print(current.coef+"X^"+current.exp+" + ");
			}else if(current.coef!=0) {
				System.out.print(current.coef);
			}
			current=current.next;
		}
		System.out.println();
	}
	public PolylinkedList sum_link(PolylinkedList b) {
		int sum[]=new int[10];
		int i=0,maxnumber;
		PolylinkedList templinkedList=new PolylinkedList();
		PolylinkedList a=new PolylinkedList();
		int tempexp[]=new int[10];
		Node2 ptr;
		a=this;
		ptr=b.first;
		while(a.first!=null) {
			b.first=ptr;
			while(b.first!=null) {
				if(a.first.exp==b.first.exp) {
					sum[i]=a.first.coef+b.first.coef;
					tempexp[i]=a.first.exp;
					a.first=a.first.next;
					b.first=b.first .next;
					i++;
				}else if(b.first.exp>a.first.exp) {
					sum[i]=b.first.coef;
					tempexp[i]=b.first.exp;
					b.first=b.first.next;
					i++;
				}else if(a.first.exp>b.first.exp) { sum[i]=a.first.coef;
				tempexp[i]=a.first.exp;
				a.first=a.first.next;
				i++;
				}
			}
		}
		maxnumber=i-1;
		for(int j=0;j
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/490282.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号