LeetCode 328. 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 ...
Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
题目名称为“奇偶链表”,意思就是把下标为奇数的节点放在链表前面(第一个节点下标为1,节点之间的相对顺序不变),这里采用的方法是用两个链表分别放置奇偶界结点,然后把“偶数链表”串在奇数链表的后面
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode* oddEvenList(ListNode* head) {
12 if(!head) return nullptr;
13
14 ListNode *odd = head;
15 ListNode *even = head->next;
16 ListNode *evenHead = even;
17
18 while(even && even->next){
19 odd->next = odd->next->next;
20 even->next = even->next->next;
21 odd = odd->next;
22 even = even->next;
23 }
24
25
26 odd->next = evenHead;
27
28 return head;
29 }
30 };
易错点:最后要把两个链表连起来;while条件中是even;处理时是先处理odd结点,再处理even结点