use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _148 method sortList.
/**
*Credit: https://discuss.leetcode.com/topic/18100/java-merge-sort-solution
* But this is not using constant space.
*/
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// Step 1: split the list into halves
ListNode prev = null;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
prev = slow;
fast = fast.next.next;
slow = slow.next;
}
prev.next = null;
// step 2: sort each half
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
// step 3: merge the two halves
return merge(l1, l2);
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _148 method merge.
private ListNode merge(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode tmp = result;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
tmp.next = l1;
l1 = l1.next;
} else {
tmp.next = l2;
l2 = l2.next;
}
tmp = tmp.next;
}
if (l1 != null) {
tmp.next = l1;
}
if (l2 != null) {
tmp.next = l2;
}
return result.next;
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _160Test method test1.
@Test
public void test1() {
headA = new ListNode(3);
headB = new ListNode(2);
headB.next = new ListNode(3);
expected = new ListNode(3);
/**
*TODO: both solution1 and solution2 are ACCEPTED on OJ, but somehow it's not passing in this unit test.
*/
// assertEquals(expected, solution1.getIntersectionNode(headA, headB));
// assertEquals(expected, solution2.getIntersectionNode(headA, headB));
assertEquals(expected, solution3.getIntersectionNode(headA, headB));
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _61Test method test1.
@Test
public void test1() {
k = 2;
expected = new ListNode(4);
expected.next = new ListNode(5);
expected.next.next = new ListNode(1);
expected.next.next.next = new ListNode(2);
expected.next.next.next.next = new ListNode(3);
head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
actual = solution1.rotateRight(head, k);
assertEquals(expected, actual);
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _725Test method test1.
@Test
public void test1() {
root = LinkedListUtils.contructLinkedList(new int[] { 1, 2, 3 });
k = 5;
actual = solution1.splitListToParts(root, k);
for (ListNode head : actual) {
ListNode.printList(head);
}
}
Aggregations