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:
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 ...
思路分析
这个题目采用和第86号题目一样的思想即可,虚拟两个链表头结点,循环遍历一遍链表, 分别用两个虚拟头结点进行连接指向,最后将两个链表进行连接即可。
具体代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(head==NULL)
return head;
ListNode* dumy_node1=new ListNode(0);
ListNode* node1_end=dumy_node1;
ListNode* dumy_node2=new ListNode(0);
ListNode* node2_end=dumy_node2;
int count=1;
while(head!= NULL)
{
if(count&0x01)
{
node1_end->next=head;
node1_end=head;
}
else
{
node2_end->next=head;
node2_end=head;
}
head=head->next;
count++;
}
if(dumy_node1->next!=NULL)
{
node1_end->next=dumy_node2->next;
node2_end->next=NULL;
return dumy_node1->next;
}
else
return dumy_node2->next;
}
};