1. 程式人生 > 其它 >【每日一題】2021年12月4日-143. 重排連結串列

【每日一題】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; } } }

本文來自部落格園,作者:劉金輝,轉載請註明原文連結:https://www.cnblogs.com/liujinhui/p/15643344.html