LeetCode Sort List

题意:给定一个list的节点,对它进行排序

解法:归并排序咯~直接上码

<span style="font-size:18px;">class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
		next = null;
	}
}

public class Solution {
	public ListNode sortList(ListNode head) {
		if (head == null || head.next == null)
			return head;
		ListNode h1 = head;
		int len = 0;
		ListNode t1 = h1, t2;
		while (t1 != null) {
			len++;
			t1 = t1.next;
		}
		if (len == 0 || len == 1) {

			return h1;
		}
		t1 = h1;
		for (int i = 1; i < len / 2; i++)
			t1 = t1.next;
		ListNode h2 = t1.next;
		t1.next = null;
		h1 = sortList(h1);
		h2 = sortList(h2);

		t1 = h1;
		t2 = h2;
		ListNode current;
		if (t1.val < t2.val) {
			head = t1;
			t1 = t1.next;
		} else {
			head = t2;
			t2 = t2.next;
		}
		current = head;

		while (t1 != null && t2 != null) {
			if (t1.val < t2.val) {
				current.next = t1;
				current = current.next;
				t1 = t1.next;
			} else {
				current.next = t2;
				current = current.next;
				t2 = t2.next;
			}
		}

		if (t1 != null) {
			current.next = t1;
		} else {
			current.next = t2;
		}
		return head;
	}

	public static void main(String[] args) {
		ListNode h1 = new ListNode(20);
		ListNode h2 = new ListNode(5);
		ListNode h3 = new ListNode(4);
		ListNode h4 = new ListNode(1);
		ListNode h5 = new ListNode(3);
		h1.next = h2;
		h2.next = h3;
		h3.next = h4;
		h4.next = h5;
		Solution s = new Solution();
		ListNode h = s.sortList(h1);
		s.print(h);
	}

	public void print(ListNode h) {
		while (h != null) {
			System.out.print(h.val + "   ");
			h = h.next;
		}
		System.out.println();
	}
}</span>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值