[LeetCode] 328. Odd Even Linked List

32 篇文章 0 订阅
19 篇文章 0 订阅

原题链接: https://leetcode.com/problems/odd-even-linked-list/

1. 题目介绍

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

给出一个单向链表,需要将所有奇数节点放在偶数节点的前面。这里的奇数和偶数,是节点的顺序编号,而不是节点的val值。
要求:空间复杂度:O(1),时间复杂度O(n),n是链表的总结点数。

Example 1:

Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL

Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on …
在奇数节点和偶数节点中的相对顺序应该保持不变。
第一个节点是奇数节点,第二个节点是偶数节点…

2. 解题思路

使用双指针法。如果要求空间复杂度为O(1),一般都会考虑使用双指针法。

首先,使用一个奇数指针 odd 指向 head ,一个偶数指针 even 指向 head.next。
接着,定义一个 cur 指针。cur 一开始指向 head.next.next。使用 cur 遍历数组,cur 每次都要走两步。这样可以使得 cur 所指的节点都是奇数节点,cur.next 指向的节点都是偶数节点。
然后,使用奇数指针 odd 和偶数指针 even 分别为奇数链表和偶数链表连接节点。每次奇数链表都会连上cur 节点,偶数链表都会连上 cur.next 节点。
最后,将两个链表拼在一起就行了。

实现代码

class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) {
        	return head;
        }

        ListNode odd = head;
        ListNode even = head.next;
        ListNode evenHead = head.next;
        ListNode cur = head.next.next;
        while(cur != null && cur.next != null){
        	odd.next = cur;
        	odd = odd.next;
        	even.next = cur.next;
        	even = even.next;
        	cur = cur.next.next;
        }
        even.next = null;
        if(cur != null){
        	odd.next = cur;
        	odd = odd.next;
        }
        odd.next = evenHead;
        
        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值