每日一道Leetcode——重排链表

it2023-05-04  70

题目: 我的解法: 思路:双指针。将每个结点存到一个list里,计算list的长度,将start指针指向头部结点0,end指针指向尾部结点list.size()-1,分别将首尾结点添加到ans。考虑边界条件,如果start最后与end相差1,说明链表总共有偶数个结点,边界条件为end-start=1;如果start等于end,说明链表总共有奇数个结点,边界条件为start=end。注意最后一个结点的next要设置为null。

/** * 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; } * } */ class Solution { public void reorderList(ListNode head) { List<ListNode> list = new ArrayList<ListNode>(); ListNode cur = head; while(cur!=null){ list.add(cur); cur = cur.next; } ListNode ans = new ListNode(0,head); int start = 0; int end = list.size()-1; while(start<=end){ if(start==end){ ans.next = list.get(start); ans.next.next =null; break; } ans.next = list.get(start); ans = ans.next; ans.next = list.get(end); ans = ans.next; if(end-start==1){ ans.next = null; break; } start++; end--; } } }

官方题解:

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; } } 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/reorder-list/solution/zhong-pai-lian-biao-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

class Solution { public void reorderList(ListNode head) { if (head == null) { return; } ListNode mid = middleNode(head); ListNode l1 = head; ListNode l2 = mid.next; mid.next = null; l2 = reverseList(l2); mergeList(l1, l2); } public ListNode middleNode(ListNode head) { ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } public void mergeList(ListNode l1, ListNode l2) { ListNode l1_tmp; ListNode l2_tmp; while (l1 != null && l2 != null) { l1_tmp = l1.next; l2_tmp = l2.next; l1.next = l2; l1 = l1_tmp; l2.next = l1; l2 = l2_tmp; } } } 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/reorder-list/solution/zhong-pai-lian-biao-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
最新回复(0)