数据结构——把数据项按顺序插入到链表中(java实现)

      今天要记录的是有序链表,前几篇讲到的链表都是无序的,说他无序就是指没有什么规律的、乱序的,将这类链表输出后会发现,其输出顺序与操作链表时的输入顺序有很大关系——要么与输入顺序顺序相同要么与输入顺序相反,具体取决于所定义的插入函数是从链表头部还是从尾部插入;实际场景下可能有序链表使用的较多,要想实现这样一个链表:创建该链表后插入的元素都能按顺序排序,则必须在定义有序链表时在插入函数定义好插入规则(decreasing or increasing),这样在插入若干个数据项后,输出该链表的数据项会发现他们是有序排序的。

      在实现有序链表的插入规则时,按照自己的逻辑去实现总是达不到真实效果,可谓险象环生:死循环(用Eclipse单步调试显示无法找到某文件)、nullPointerException、只输出一个数据项、输出时少一个数据项、只输出最后插入的两个数据项,凡此足足,不一而足,按照书上的去做完全没有问题,可当碰到我怎么才能想到呢,不管他了,先记录下再说,代码如下:

class Link
{
	public int iData;
	public double dData;
	public Link next;
//-------------------------------------
	public Link(int iData, double dData)
	{
		this.iData = iData;
		this.dData = dData;
	}
//-------------------------------------
	public void displayLink()
	{
		System.out.print("{" + iData + ", " + dData + "}");
	}
}

class LinkList
{
	private Link first;
	//--------------------
	public LinkList()
	{
		first = null;
	}
	//--------------------
	public boolean isEmpty()
	{
		return (first == null);
	}
	//---------------------
	public void insertInOrder(int iData, double dData)
	{
		Link newLink = new Link(iData, dData);
		Link previous = null; //if you write like this: previous=first, will executed forever;
		Link current = first;
		
		while(current!=null && current.iData<newLink.iData)
		{
			previous = current;
			current = current.next;  // go to next item
		}
		
		if(previous==null)
		{
			first = newLink;
		}
		else 
		{
			previous.next = newLink;
			
		}
		newLink.next = current;
		
	}
	//-----------------------------------------------------------------------
	public void insertFirst(int iData, double dData)
	{
		Link newLink = new Link(iData, dData);
		Link current = first;
		if(first==null)
		{
			first = newLink;
		}
		else
		{
			first = newLink;
			newLink.next = current;
		}
	}
	//-----------------------------------------------------------------------
	public void displayList()
	{
		Link current = first;
		if(current == null)
		{
			System.out.println("Your list is empty, please show something!");
		}
		else
		{
			System.out.println("List in order (front-->rear): ");
			while(current!=null)
			{
				current.displayLink();
				current = current.next;
			}
			System.out.println("");
		}
	}

		

}

public class LinkListApp
{
	public static void  main(String[] args)
	{
		LinkList theList = new LinkList(); //make new list

		theList.insertInOrder(189,256.66); //insert four items, will be in an increasing order
		theList.insertInOrder(12,23.66);    
		theList.insertInOrder(4,23.66); 
		theList.insertInOrder(5,23.66);
		

		theList.displayList();		//display list
	}
}

插入四个数据项后,在Eclipse中的运行效果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值