题目:
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 1:
Input: 1->2->3->4->5->NULL
Output: 2->3->6->7->1->5->4->NULL
此题需要将奇数编号结点放在一起,将偶数编号结点放在一起。可以将原链表分成奇数编号结点链表和偶数结点编号链表,最后将奇数编号结点链表尾结点指向偶数结点编号链表,即可解决问题。
public class OddEvenLinkedList {
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null || head.next.next == null)
return head;
ListNode evenHead = head.next;
ListNode cur = head;
ListNode node = evenHead;
while (cur.next != null && node.next != null) {
cur.next = cur.next.next;
node.next = node.next.next;
cur = cur.next;
node = node.next;
}
cur.next = evenHead;
return head;
}
}
本文介绍了一种链表操作算法,将链表中的奇数编号节点与偶数编号节点分别进行分组,并最终合并为一个新的链表。该算法采用原地修改方式,空间复杂度为O(1),时间复杂度为O(nodes)。
482

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



