LeetCode:328. Odd Even Linked List

0X01 题目

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.

Example::
Given 1->2->3->4->5->NULL,
return 1->3->5->2->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 …

0X02 题意

题目要求是将下标为奇数的节点和下标为偶数的节点分开,需要注意的是是下标的奇偶,而不是数值的奇偶。

第一个node的下标视为奇数,第二个视为偶数,而不是从0开始。

另外要求了时间复杂度和空间复杂度。

0X03 题解

1.迭代(Dante:Java)

在纸上比比划划出来了一个解法,思路挺简单的,就是需要两个指针,oddLast指向当前循环的最后一个奇数,evenLast指向最后一个偶数。

1->2->3->4->5->NULL为例,第一次循环的时候oddLast指向1,evenLast指向2,tmpNode指向4。

第一次循环结束后,链表应该是这样的:1->3->2->4->5->NULL,此时oddLast指向3,evenLast指向4。

然后继续循环即可。

public class Solution {
    public ListNode oddEvenList(ListNode head) {
        if(head == null)
            return head;
        ListNode oddLast = head;
        ListNode evenLast = head.next;
        ListNode tmpNode;
        while(evenLast != null && evenLast.next != null) {
            tmpNode = evenLast.next.next;
            evenLast.next.next = oddLast.next;
            oddLast.next = evenLast.next;
            evenLast.next = tmpNode;
            evenLast = evenLast.next;
            oddLast = oddLast.next; 
        }
        return head;

    }
}

2016-08-04 19:39:60 hzct

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值