【每日一题】2021年12月4日-143. 重排链表

 

 

/**
 * 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; }
 * }
 */

//方法1:放入ArrayList
class Solution {
    public void reorderList(ListNode head) {
        if(head == null) {
            return;
        }
        List<ListNode> list = new ArrayList<ListNode>();
        ListNode node = head;
        while(node != null) {
            list.add(node);
            node = node.next;
        }
        int i = 0, j = list.size() - 1;
        while(i < j) {
            list.get(i).next = list.get(j);
            i++;
            if(i == j) {
                break;
            }
            list.get(j).next = list.get(i);
            j--;
        }
        list.get(i).next = null;
    }
}

//方法2:递归

//方法3:双端队列

//方法4:找中点mid,后部分反转reverse,两部分合并merge
class Solution {
    public void reorderList(ListNode head) {
        if(head == null) {
            return;
        }
        //找中点
        ListNode mid = middle(head);
        ListNode l1 = head;
        ListNode l2 = mid.next;
        mid.next = null;
        l2 = reverse(l2);
        merge(l1, l2);
    }

    public ListNode middle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        //注意循环条件不是fast!=null,而是next和next.next
        while(fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public void merge(ListNode l1, ListNode l2) {
        ListNode l1_Next;
        ListNode l2_Next;
        while(l1 != null && l2 != null) {
            l1_Next = l1.next;
            l2_Next = l2.next;
            l1.next = l2;
            l1 = l1_Next;
            l2.next = l1_Next;
            l2 = l2_Next;
        }
    }
}

 

posted @ 2021-12-04 21:41  哥们要飞  阅读(24)  评论(0编辑  收藏  举报