本文主要是介绍LeetCode 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
.
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 ...
题意:
就是将一个单链表中的坐标为奇数的节点按照原来的顺序放到前面,将原来是偶数序的节点放到后面。并且都要求奇数和偶数序列的顺序要保持不变。
题解:
我们可以按照设置两个单链表,一个专门用于放置奇数节点,另一个用于放置偶数节点,最后只要将这个奇数节点的末尾直接指向欧树节点的头节点即可,即可完成工作。
public class Solution
{public static ListNode oddEvenList(ListNode head) {if (head == null || head.next == null)return head;ListNode even_head = head.next;ListNode odd = head, even = even_head;while(even != null && even.next != null) {odd.next = even.next;even.next = even.next.next;odd = odd.next;even = even.next;}odd.next = even_head;return head;}
}
这篇关于LeetCode Odd Even Linked List的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!