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 ...
分析:
简单模拟思想,
申请两个指针,一个总是指向当前将要建立连接的奇数节点,一个偶数...最后联立奇数链表和偶数链表即可。
显然,先建立奇数指针,再偶数指针....
建立奇数指针时,看偶数指针的下一个位置是否存在,存在就建立连接,
并将奇数指针移动当当前奇数节点!
如果不存在就完成偶数链和奇数链的最终联立!
偶数指针同理!
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || head->next==NULL || head->next->next==NULL)
return head;
ListNode* oddNode=head;//奇数
ListNode* evenNode=head->next;//偶数
ListNode* evenhead=head->next;//偶数头
while(true)
{
if(evenNode->next!=NULL)//如果存在就建立连接
{
oddNode->next=evenNode->next;
oddNode=evenNode->next;//偶数尾巴
}else
{
oddNode->next=evenhead;
evenNode->next=NULL;
break;//建立偶数链表与奇数链表的连接退出循环
}
if(oddNode->next!=NULL)
{
evenNode->next=oddNode->next;
evenNode=oddNode->next;
}else
{
oddNode->next=evenhead;
evenNode->next=NULL;
break;//建立......连接退出循环
}
}
return head;
}
};
简化代码:
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || head->next==NULL || head->next->next==NULL)
return head;
ListNode* oddNode=head;//奇数
ListNode* evenNode=head->next;//偶数
ListNode* evenhead=head->next;//偶数头
while(evenNode!=NULL && evenNode->next !=NULL)//不管链表有奇数个还是偶数个节点都以偶数指针作为截止条件
{
oddNode->next=evenNode->next;
oddNode=evenNode->next;//偶数尾巴
evenNode->next=oddNode->next;
evenNode=oddNode->next;
}
oddNode->next=evenhead;
return head;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50611707
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895