使用队列输出n层杨辉三角

package six;
/*
 * 2.杨辉三角,建议:输出15层,用链表,用队列
 * 思路:
 * 创建一个队列,先输入一个1,当队列不为空的时候
 */
public class Triangle
{
	public static void main(String[] args)
	{
		Integer[] a=new Integer[20];
		team<Integer> team=new  team<Integer>(a);
		team.enqueue(1);
		int floor=15;
		list<Integer> list=new list<Integer>();
		for(int x=0;x<floor;x++)
		{
			while(!team.isempty())
			{
				list.Insert(list.length(), new Node<Integer>(team.outqueue()));				
			}
			list.show();
			if(list.length()<2)
			{
				team.enqueue(1);team.enqueue(1);
			}
			else
			{
				team.enqueue(1);
				Node<Integer> node=list.head.next;
				while(node.next!=null)
				{
					team.enqueue(node.data+node.next.data);
					node=node.next;
				}
				team.enqueue(1);
			}
			list.head.next=null;
		}
		
	}
}
class list<T>
{
	
	Node<T> head;
	public list()
	{
		this.head=new Node<T>();
	}
	//在其后面插入一个节点
	public void Insert(int x,Node<T> node)
	{
		int falg=-1;  //标志位置
		Node<T> cur =head;
		while(falg<x-1&&cur!=null)
		{
			cur=cur.next;falg++;
		}
		if(falg>x-1||cur==null)
		{
			System.out.println("a error location");
		}
		else
		{
			node.next=cur.next;
			cur.next=node;
		}
	}
	public int length()
	{
		Node<T> node=head.next;
		int length=0;
		while(node!=null)
		{
			node=node.next;
			length++;
		}
		return length;
	}
	public void show()
	{
		Node<T> cur=this.head.next;
		for(int x=0;x<length();x++)
		{
			System.out.print(cur.data+"  ");
			cur=cur.next;
		}
		System.out.println("结束");
	}


}
class Node<T>
{
	T data;
	Node<T> next;
	public Node()
	{
		super();
	}
	public Node(T data)
	{
		super();
		this.data = data;
	}
}
class team<T>
{
	public T[] tarray;	 //缓存区
	public int head;//头删除
	public int tail;//尾增加
	public team(T[] t)
	{
		this.tarray = t;
	}
	public boolean enqueue(T t)
	{
		if((tail+1)%tarray.length!=head)
		{
			tarray[(tail++)%tarray.length]=t;
			return true;
		}
		else
		return false;
	}
	public T outqueue()
	{
		T t=null;
		if(tail!=head)
		{
			t=tarray[(head++)%tarray.length];
		}
		return t;
	}
	public boolean isempty()
	{
		return tail==head;
	}
}

发布了133 篇原创文章 · 获赞 37 · 访问量 4744

猜你喜欢

转载自blog.csdn.net/qq_43416157/article/details/104233380
今日推荐