码迷,mamicode.com
首页 > Windows程序 > 详细

LeetCode 328. Odd Even Linked List C#

时间:2016-12-14 02:17:00      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:ons   eve   class   分享   ima   size   was   height   eth   

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 ...

 

Solution 1):

    技术分享

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

 

 Solution 2):

 1->2->3->4->5->6->7    to odd: 1->3->5  and even 2->4->6;

then return odd ->even;

 

 1 public class Solution {
 2     public ListNode OddEvenList(ListNode head) {
 3         if(head==null)
 4         {
 5             return head;
 6         }
 7         ListNode odd = head;
 8         ListNode even = head.next;
 9         ListNode evenHead = even;
10         while(even!=null&&even.next!=null)
11         {
12             odd.next = even.next;
13             odd = odd.next;
14             even.next = odd.next;
15             even = even.next;
16         }
17         odd.next = evenHead;
18         return head;
19     }
20 }

 

              

 

 

    


 

LeetCode 328. Odd Even Linked List C#

标签:ons   eve   class   分享   ima   size   was   height   eth   

原文地址:http://www.cnblogs.com/MiaBlog/p/6175697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!