[LeetCode][数论]Odd Even Linked List

来源:互联网 发布:send to kindle mac 编辑:程序博客网 时间:2024/06/05 16:35

题目描述:

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.


思路:

前提:链表结构,改变现有排列顺序将奇数号结点连接放在偶数号结点前面

过程:分组问题,通过求余判定奇数号还是偶数号,新建两个头结点实现奇数结点和偶数结点的串联,然后将偶数结点放在奇数结点后面


代码实现:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    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;    }}



0 0