按照左右區間的方式重新組合單鏈表
阿新 • • 發佈:2019-01-07
class Solution { private static ListNode split(ListNode head) { if (head == null || head.next == null) { return head; } ListNode pre = null; ListNode slow = head; ListNode fast = head.next.next; int num = 2; while (fast != null) { pre = slow; slow = slow.next; if (fast.next == null) { num += 1; break; } num += 2; fast = fast.next.next; } if (num % 2 == 0) { ListNode result = slow.next; slow.next = null; return result; } pre.next = null; return slow; } private static ListNode merge(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } ListNode head = new ListNode(-1); ListNode p = head; while (l1 != null) { ListNode l1Next = l1.next; ListNode l2Next = l2.next; p.next = l1; p = p.next; p.next = l2; p = p.next; l1 = l1Next; l2 = l2Next; } p.next = l2; return head.next; } private static ListNode function(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return null; } return merge(head, split(head)); } private static void print(ListNode head, Integer limit) { if (limit == null) { limit = Integer.MAX_VALUE; } while (head != null && limit -- > 0) { System.out.println(head.val); head = head.next; } } public static void main(String[] args) { ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); ListNode n4 = new ListNode(4); ListNode n5 = new ListNode(5); ListNode n6 = new ListNode(6); ListNode n7 = new ListNode(7); ListNode n8 = new ListNode(8); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; // n6.next = n7; // n7.next = n8; ListNode head = function(n1); print(head, 100); } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }