LeeCode148. 排序链表(两种解法)

148. 排序链表

链接:https://leetcode-cn.com/problems/sort-list/solution/148-pai-xu-lian-biao-by-oyzg-sta1/
解题思路
解法一:
用一个容器来装入每个节点,然后再排序,我这里使用的是ArrayList

解法二:
插入排序

代码:
解法一:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
		ArrayList<ListNode> list = new ArrayList<ListNode>();
		ListNode cur = head;
		while(cur != null) {
			list.add(cur);
			ListNode ln = cur;
			cur = cur.next;
			ln.next = null;
		}
		list.sort(new Comparator<ListNode>() {

			@Override
			public int compare(ListNode o1, ListNode o2) {
				// TODO Auto-generated method stub
				return o1.val - o2.val;
			}
		
		});
		ListNode node = new ListNode(0);
		cur = node;
		for(ListNode l : list) {
			cur.next = l;
			cur = cur.next;
		}
		return node.next;
    }
	
	
}

	public ListNode sortList(ListNode head) {
		if(head == null) return null;
		return sortList(head, head);
    }
	
	public ListNode sortList(ListNode head, ListNode tail) {
		if(tail.next == null) return head;
		ListNode node = tail.next;
		if(node.val >= tail.val) return sortList(head, node);
		tail.next = tail.next.next;
		if(node.val <= head.val) {
			node.next = head;
			return sortList(node, tail);
		}
		ListNode cur = head;
		while(cur != null) {
			if(cur.next.val >= node.val) {
				node.next = cur.next;
				cur.next = node;
				break;
			}
			cur = cur.next;
		}
		return sortList(head, tail);
	}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值