注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
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 …
/**
* 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) {
ListNode odd = head, evenHead = head.next, even = odd.next;
while (odd.next != null && even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
}
return head;
}
}
本文介绍了一种算法,该算法接收一个单链表作为输入,并将所有奇数位置的节点分组在一起,随后是所有偶数位置的节点。整个过程在原地完成,不使用额外的空间。提供了具体实现代码,确保了空间复杂度为O(1),时间复杂度为O(nodes)。
516

被折叠的 条评论
为什么被折叠?



