日期:2014-05-17 浏览次数:20864 次
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { //新建一个表达式和一些新项,并向表达式中插入这些项 MyExpression me = new MyExpression(); MyItem item1 = new MyItem(2, 0); MyItem item2 = new MyItem(2, 3); MyItem item3 = new MyItem(2, 1); MyItem item4 = new MyItem(2, 5); MyItem item5 = new MyItem(2, 2); me.InsertItem(item1); me.InsertItem(item2); me.InsertItem(item3); me.InsertItem(item3); me.InsertItem(item4); me.InsertItem(item5); foreach (MyItem mi in me.Expression) { Console.Write(mi.Num + "*x^" + mi.Exp + "+"); } Console.ReadKey(); } } /// <summary> /// 表达式类,用于存储所有的项 /// </summary> class MyExpression { private List<MyItem> _expression;//用于存储表达式的项 internal List<MyItem> Expression { get { return _expression; } set { _expression = value; } } /// <summary> /// 初始化一个表达式 /// </summary> public MyExpression() { Expression = new List<MyItem>(); MyItem item = new MyItem(0, 0); Expression.Add(item); } /// <summary> /// 插入一个项,根据指数来确定插入新项还是与原有项相加 /// </summary> /// <param name="item"></param> public void InsertItem(MyItem item) { int length = Expression.Count; bool hasInserted = false; for (int i = 0; i < length; i++) { if (Expression[i] > item) //当前项指数比插入项大时,插到当前项的位置 { Expression.Insert(i, item); hasInserted = true; break; } if (Expression[i].Exp == item.Exp)//指数相等时相加 { Expression[i].Num += item.Num; hasInserted = true; break; } } if (!hasInserted) { Expression.Add(item);//指数比已知项都要大,插到表达式尾部 } } protected void Sort() { this.Expression.Sort(); } } /// <summary> /// 结点类,存储每一项 /// </summary> class MyItem : IComparable<MyItem> { private int _num;//倍娄 public int Num { get { return _num; } set { _num = value; } } private int _exp;//指数 public int Exp { get { return _exp; } set { _exp = value; }