leetcode链接:143. 重排链表
题目分析



方案一
遍历原链表,将其放入到列表中,然后重新生成数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public void reorderList(ListNode head) { List<ListNode> list = new ArrayList<>();
ListNode tempNode = new ListNode(); tempNode.next = head;
while (head != null) { list.add(head); head = head.next; }
int start = 0, end = list.size() - 1; while (start < end) { tempNode.next = list.get(start); tempNode = tempNode.next; tempNode.next = list.get(end); tempNode = tempNode.next; start++; end--; } if (start == end) { tempNode.next = list.get(start); tempNode = tempNode.next; } tempNode.next =null; } }
|
结果
解答成功:
执行耗时:2 ms,击败了43.81% 的Java用户
内存消耗:44.5 MB,击败了57.03% 的Java用户
分析
时间复杂度:
O( n )
空间复杂度:
O( n )
官方题解
https://leetcode.cn/problems/reorder-list/solution/zhong-pai-lian-biao-by-leetcode-solution/
方法一:线性表
因为链表不支持下标访问,所以我们无法随机访问链表中任意位置的元素。
因此比较容易想到的一个方法是,我们利用线性表存储该链表,然后利用线性表可以下标访问的特点,直接按顺序访问指定元素,重建该链表即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| 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) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|

方法二:寻找链表中点 + 链表逆序 + 合并链表

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| 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) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
