首页 > 其他 > 详细

LeetCode Odd Even Linked List

时间:2016-03-27 07:09:26      阅读:237      评论:0      收藏:0      [点我收藏+]

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

题目:

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.

题解:

要归类的是node的index而不是node的value. 双指针, 一个指向odd位置, 一个指向even位置.

Time Complexity: O(n). Space: O(1).

AC Java:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode oddEvenList(ListNode head) {
11         if(head == null || head.next == null || head.next.next == null){
12             return head;
13         }
14         ListNode oddHead = head;
15         ListNode evenHead = head.next;
16         ListNode oddCur = oddHead;
17         ListNode evenCur = evenHead;
18         while(evenCur != null && evenCur.next != null){
19             oddCur.next = evenCur.next;
20             evenCur.next = evenCur.next.next;
21             oddCur = oddCur.next;
22             evenCur = evenCur.next;
23         }
24         oddCur.next = evenHead;
25         return oddHead;
26     }
27 }

 

LeetCode Odd Even Linked List

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/5324744.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!