leetcode地址:
https://leetcode.com/problems/odd-even-linked-list/description/
描述:
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:1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output:2->3->6->7->1->5->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 ...
分析:
这题感觉没什么难度,唯一有点难度的地方在于你最好不要创建新的节点,而仅仅是改变节点之间的连接关系,即只通过改变节点的next指针来重建链表顺序,这样才能达到空间复杂度为O(1)的要求。这题有两种,一种要求按照元素的下标的奇偶性进行排序,另一种按照节点的val值的奇偶性进行重排,区别不大,无非是对奇偶性的判断略有区别。
我这里仍然使用了虚拟头结点来减小代码实现的复杂性。
代码:
public boolean isPalindrome(ListNode head) {
if (null == head) {
return true;
}
// 切分链表
ListNode fast = head, slow = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode right = slow.next;
slow.next = null;
right = reverse(right);
while (right != null && head != null) {
if (right.val != head.val) {
return false;
}
right = right.next;
head = head.next;
}
return true;
}
public ListNode reverse(ListNode list) {
ListNode newHead = null;
while (list != null) {
ListNode next=list.next;
list.next = newHead;
newHead = list;
list = next;
}
return newHead;
}