Insertion Sort List

本文介绍了一种使用插入排序算法对链表进行排序的方法,并提供了一个具体的实现示例。

题目描述:

Sort a linked list using insertion sort.


插入排序,题目很简单,只是换成链表实现而已。


代码如下所示


public ListNode insertionSortList(ListNode head) {
	ListNode cur=head;
	int sum=0;
	while(cur!=null){
		cur=cur.next;
		sum++;
	}
	for(int i=2;i<=sum;i++){
		int n=i;
		cur=head;
		while(n>1){
			cur=cur.next;
			n--;
		}
		head=insert(head, cur);
	}
	return head;
}

public  ListNode insert(ListNode head,ListNode insertNode){
	ListNode start=new ListNode(-1);
	start.next=head;
	ListNode pre=start,cur=head,last=null,next=null;
	//获得insertNode的前一个节点
	while(cur!=insertNode){
		cur=cur.next;
		pre=pre.next;
	}
	last=pre;
	pre=start;cur=head;
	while(cur!=insertNode){
		if(cur.val<=insertNode.val){
			cur=cur.next;
			pre=pre.next;
		}else{
			next=insertNode.next;
			pre.next=insertNode;
			insertNode.next=cur;
			break;
		}
	}
	if(cur==insertNode)
		return head;
	else{
		last.next=next;
		return start.next;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值