- 题目:将连接按照规则重新排列(链表的第一个元素的下一个元素为倒数第1个元素,链表的第二个元素的下一个元素是倒数第2个元素)
- 难度:Medium
- 思路:先将后半部分的链表进行反转,然后调整前半部分和后半部分的指针指向
- 代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null){
return;
}
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = slow;
ListNode curr = mid.next;
if(curr != null){
ListNode temp = curr.next;
curr.next = null;
curr = temp;
}
while(curr != null){
ListNode temp = curr.next;
curr.next = mid.next;
mid.next = curr;
curr = temp;
}
ListNode left = head;
ListNode right = mid.next;
while(right != null){
mid.next = right.next;
right.next = left.next;
left.next = right;
left = right.next;
right = mid.next;
}
}
}