BM14 链表的奇偶重排

在这里插入图片描述
第一种方法:使用队列,时间复杂度O(n),空间复杂度O(n)

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode oddEvenList (ListNode head) {
        // write code here
        // 小于两个节点直接返回
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        //用队列
        Queue<ListNode> queue1 = new LinkedList<ListNode>();
        Queue<ListNode> queue2 = new LinkedList<ListNode>();
        int i = 1;
        while (head != null) {
            if (i % 2 != 0) {
                queue1.add(head);
            } else {
                queue2.add(head);
            }
            head = head.next;
            i++;
        }
        ListNode pre = new ListNode(-1);
        ListNode node = pre;
        while (!queue1.isEmpty()) {
            pre.next = queue1.poll();
            pre = pre.next;
        }
        while (!queue2.isEmpty()) {
            pre.next = queue2.poll();
            pre = pre.next;
        }
        //防止尾部循环
        pre.next = null;
        return node.next;
    }
}

方法二:声明前后指针,一个奇一个偶,每次都是跨两步,最后再把偶链表放到奇链表尾部即可,时间复杂度O(n),空间复杂度O(1)

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode oddEvenList (ListNode head) {
        // write code here
        // 小于两个节点直接返回
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        //声明前后指针,一个奇一个偶,每次都是跨两步,最后再把偶链表放到奇链表尾部即可
        ListNode node1 = head;
        ListNode node2 = head.next;

        //在声明两个指针保存node1和node2的头部,因为在移动过程中会变动
        ListNode node3 = node1;
        ListNode nodo4 = node2;
        while (node2 != null && node2.next != null) {
            node1.next = node1.next.next;
            node2.next = node2.next.next;
            node1 = node1.next;
            node2 = node2.next;
        }
        //将node2的头部放到node1的尾部
        node1.next = nodo4;
        //返回node1的头部
        return node3;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值