1.3排序链表(SortedSinglyLinkedList)

本文介绍了一种排序单链表的实现方式,通过重载compareTo()方法确保元素按升序排列,并提供了插入、删除等操作的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

排序单链表(升序排列)在单链表的基础上插入时需要找到比自己大的的第一个节点,然后插在该节点的前面。但是要重载一下节点数据项的数据类型(自定义类型)的compareTo()方法。代码如下:

public class SortedSinglyLinkedList<T extends Comparable<T>> extends SinglyLinkedList<T>
{
	public SortedSinglyLinkedList()
	{
		super();
	}
	//默认构造函数调用父类构造方法
	
	public SortedSinglyLinkedList(T[] element)
	{
		super();
		if(element!=null)
		{
			for(int i=0;i<element.length;i++)
				this.insert(element[i]);
		}
	}
	
	public SortedSinglyLinkedList(SortedSinglyLinkedList<T> list)
	{
		super(list);
	}
	//深拷贝构造函数,调用父类同参数构造函数
	
	public void insert(T x)
	{
		if(x==null)
			return;
		Node<T> font=this.head;
		Node<T> p=font.next;
		while(p!=null && p.data.compareTo(x)<0)
		{
			font=p;
			p=p.next;
		}
		font.next=new Node<T>(x,p);
	}
	//重载父类方法insert(int i,T x)为按大小insert()
	
	public void insert(int i,T x)
	{
		throw new UnsupportedOperationException("insert(int i,T x)");
	}
	
	public void append(T x)
	{
		throw new UnsupportedOperationException("append(T x)");
	}
	
	public void remove(T x)
	{
		if(x==null)
			return;
		Node<T> front=this.head;
		Node<T> p=front.next;
		while(p!=null && p.data.compareTo(x)<0)
		{//寻找待删除的节点,p作为数据项检查节点,front作为前驱标记目标前置项,便于指针的断开和链接
			front=p;
			p=p.next;
		}
		if(p!=null && p.data.compareTo(x)==0)
			front.next=p.next;
	}
	
	public static Integer[] random(int n)
	{
		Integer[] intArray=new Integer[n];
		for(int i=0;i<n;i++)
		{
			intArray[i]=new Integer((int)(Math.random()*100));
			
		}
		return intArray;
	}
}

测试代码如下:

public static void main(String[] args) 
	{
		SortedSinglyLinkedList<Integer> list=new SortedSinglyLinkedList<Integer>(SortedSinglyLinkedList.random(10));
		System.out.println("list:"+list.toString());
		list.insert(55);
		System.out.println("list:"+list.toString());
		list.remove((Integer)55);
		System.out.println("list:"+list.toString());
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值