LeetCode 328. Odd Even Linked List C#
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 328. Odd Even Linked List C#相关的知识,希望对你有一定的参考价值。
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#的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-328. Odd Even Linked List
Leetcode 328. Odd Even Linked List
LeetCode OJ 328Odd Even Linked List
LeetCode OJ 328Odd Even Linked List