当前位置:   article > 正文

【Leetcode之链表】0143 重排链表

【Leetcode之链表】0143 重排链表

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/reorder-list

实现语言:Java

文章记录的是第一次做力扣题时的代码,之后做题的代码放在GitHub上了,由于博客中的文章有点多,挨个修改费时费力,博客中写的有关力扣的文章和GitHub中的代码并不完全对应。力扣题GitHub地址

题目

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
  • 1
  • 2
  • 3

方法:双指针(快慢指针)

代码实现

/**
 * 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 || head.next==null) return ;
        // find the second half of the list
        ListNode fast = head;
        ListNode slow = head;
        while (fast!=null && fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
        }
       
        //reverse the second of the list
        ListNode head2 = slow.next;
        slow.next = null;
        head2 = reverse(head2);
        // merge
        merge(head, head2);     
    }
    // no head node
    public void merge(ListNode head, ListNode head2) {
        ListNode p = head;
        ListNode q = head2;
        ListNode tmp;
        while (p!=null && q!=null) {
            tmp = q.next;
            q.next = p.next;
            p.next = q;
            p = p.next.next;
            q = tmp;
        }
    }
    // no head node
    public ListNode reverse(ListNode head) {
       if (head==null || head.next==null) return head;
       ListNode p = head.next;
       head.next = null;
       ListNode tmp;
       while (p!=null){
           tmp = p.next;
           p.next = head;
           head = p;
           p = tmp;
       }
       return head;
    }
}
  • 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
  • 56

时间复杂度:O(n)

空间复杂度:O(1)

执行用时:2 ms

内存消耗:41.2 MB

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/226771
推荐阅读
相关标签
  

闽ICP备14008679号