LeetCode:328. Odd Even Linked List

来源:互联网 发布:saas企业级软件服务 编辑:程序博客网 时间:2024/06/10 00:32

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
原创粉丝点击