/**
* 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) {
ListNode slow = head, quick = head;
ListNode tmp = new ListNode();
while(quick.next != null && quick.next.next != null) { //找到中节点
slow = slow.next;
quick = quick.next.next;
}
ListNode reverseAfter = reverse(slow); //反转
ListNode reversetmp = null;
ListNode cur = head;
while(cur != null && reverseAfter != null){ //合并
tmp = cur.next;
reversetmp = reverseAfter.next;
cur.next = reverseAfter;
reverseAfter.next = tmp;
reverseAfter = reversetmp;
cur = tmp;
}
}
public ListNode reverse (ListNode head) {
if(head == null || head.next == null) return head;
ListNode res = reverse(head.next);
head.next.next = head;
head.next = null;
return res;
}
}
Leetcode 143. 重排链表
最新推荐文章于 2024-07-18 01:42:44 发布