题目
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
解题思路1:
- 遍历链表求表长,然后申请一个同样大小的数组,依次把链表元素存入数组
- 在数组中完成链表的重连即可。
代码实现:
/**
* 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) {
if(head == null){
return;
}
int n = 0;
ListNode cur = head;
while(cur!=null){
n++;
cur = cur.next;
}
ListNode[] arr = new ListNode[n];
cur = head;
for(int k=0;k<n;k++){
arr[k] = cur;
cur = cur.next;
}
int i = 0,j = arr.length-1;
while(i<j){
arr[i].next = arr[j];
i++;
if(i == j){
break;
}
arr[j].next = arr[i];
j--;
}
arr[i].next = null;
}
}
复杂度分析:
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( N ) O(N) O(N)
解题思路2:
- 寻找链表的中间结点
- 把链表右半部分逆序
- 合并左右链表即可。
例子: 1 -> 2 -> 3 -> 4 -> 5 -> 6
第一步,根据中间结点将链表拆分成左右两个链表
1 -> 2 -> 3
4 -> 5 -> 6
第二步,将第二个链表逆序
1 -> 2 -> 3
6 -> 5 -> 4
第三步,依次连接两个链表
1 -> 6 -> 2 -> 5 -> 3 -> 4
/**
* 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) {
if (head == null) {
return;
}
//1.查找链表的中间结点
ListNode middle = middleNode(head);
ListNode left = head;
ListNode right = middle.next;
middle.next = null;
//2.右半部分链表逆序
right = reverseList(right);
//3.合并左右链表
merge(left,right);
}
/**
* 查找链表的中间结点
* @param head
* @return
*/
public ListNode middleNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
/**
* 反转链表
* @param head
* @return
*/
public ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode next = null;
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
/**
* 合并链表
* @param left
* @param right
*/
public void merge(ListNode left,ListNode right){
ListNode next = null;
while(right != null){
next = left.next;
left.next = right;
left = right;
right = next;
}
}
}
复杂度分析:
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( 1 ) O(1) O(1)