-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortList.java
80 lines (69 loc) · 1.8 KB
/
sortList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class sortList {
public static ListNode sortList(ListNode head)
{
if(head==null||head.next==null)
{
return head;
}
ListNode middle = splitList(head);
ListNode firstList = head;
ListNode secondList = middle.next;
middle.next = null;
ListNode first = sortList(firstList);
ListNode second = sortList(secondList);
ListNode mergedArray = mergeList(first,second);
return mergedArray;
}
public static ListNode splitList(ListNode head)
{
ListNode prevSlow = null;
if(head==null||head.next==null)
return head;
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null)
{
prevSlow = slow;
slow=slow.next;
fast=fast.next.next;
}
return prevSlow;
}
public static ListNode mergeList(ListNode first, ListNode second)
{
if(first==null)
return second;
if(second==null)
return first;
if(first.val<second.val)
{
first.next = mergeList(first.next,second);
return first;
}
else
{
second.next = mergeList(second.next,first);
return second;
}
}
public static void main(String[] args) {
ListNode x1 = new ListNode(2);
ListNode x2 = new ListNode(1);
/*ListNode x3 = new ListNode(5);
ListNode x4 = new ListNode(4);
ListNode x5 = new ListNode(2);
ListNode x6 = new ListNode(6);*/
x1.next = x2;
x2.next = null;
/*x3.next = x4;
x4.next = x5;
x5.next = x6;
x6.next = null;*/
ListNode r = sortList(x1);
while(r!=null)
{
System.out.print(r.val+ " ");
r=r.next;
}
}
}