LeetCode:Odd Even Linked List - 链表内元素按奇偶位置重新排序

1、题目名称

Odd Even Linked List(链表内元素按奇偶位置重新排序)

2、题目地址

https://leetcode.com/problems/odd-even-linked-list/

3、题目内容

英文:

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.

中文:

给出一个链表,将所有奇数位置的节点和偶数位置的节点都归拢到一起,将偶数位置的节点放在所有奇数位置节点的后面。例如,给出链表1->2->3->4->5->NULL,应返回链表1->3->5->2->4->NULL。注意

4、解题方法

我使用的方法是,新建两个链表,分别存储奇数位置和偶数位置的节点,最后将两个链表接上,得到的结果即为所求。

Java代码如下:

/**
 * @功能说明:LeetCode 328 - Odd Even Linked List
 * @开发人员:Tsybius2014
 * @开发时间:2016年1月21日
 */
public class Solution {
    /**
     * 将一个链表内的奇数元素放在前面,偶数元素放在后面
     * @param head 链表首节点
     * @return 转换后的链表
     */
    public ListNode oddEvenList(ListNode head) {
        //输入合法性判断
        if (head == null) {
            return null;
        } else if (head.next == null) {
            return head;
        }
        ListNode odd = new ListNode(0);  //奇数链表:仅存放奇数位置节点
        ListNode oddCurr = odd;          //奇数链表的链表尾节点
        ListNode even = new ListNode(0); //偶数链表:仅存放偶数位置节点
        ListNode evenCurr = even;        //偶数链表的链表尾节点
        //分别生成奇数链表和偶数链表
        ListNode tmp = head;
        int counter = 0;
        while (tmp != null) {
            counter++;
            if (counter % 2 != 0) {
                oddCurr.next = new ListNode(tmp.val);
                oddCurr = oddCurr.next;
            } else {
                evenCurr.next = new ListNode(tmp.val);
                evenCurr = evenCurr.next;
            }
            tmp = tmp.next;
        }
        oddCurr.next = even.next; //偶数链表接在奇数链表后面
        return odd.next;
    }
}

END

你可能感兴趣的:(LeetCode,链表,奇数,偶数,#328)