#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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 ...
分析:题目要求将所有偶数的结点放置在所有奇数结点的后面,
并且偶数结点和奇数结点本身各自维持自己的相对顺序不变。
在常量空间复杂度和线性时间复杂度下求解。
本来最简单的方法是将奇数结点和偶数结点分别存放至奇数结点链表
,偶数结点链表,然后将奇数结点链表中最后一个结点连接偶数结点
链表表头即可。
应该是拆分出两个链表用上述方法来做。
设置两个指针odd,even,odd指针指向起始奇数结点,
even指针指向起始偶数结点,两个指针每次走两步,
并记录走两步后的下一个指针,然后
还需要记录偶数结点链表的头结点
1->2->3->4->5->NULL
1->2->3->4->5->6->NULL
输入:
1(结点个数)
1(每个结点的值)
2
1 2
5
1 2 3 4 5
6
1 2 3 4 5 6
输出:
1
1 2
1 3 5 2 4
1 3 5 2 4 6
关键:
1 将奇数结点和偶数结点分别存放至奇数结点链表
,偶数结点链表,然后将奇数结点链表中最后一个结点连接偶数结点
链表表头即可。
偶数结点不空,奇数结点指向偶数结点的下一个结点
奇数结点不空,偶数结点指向奇数结点的下一个结点
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if((!head) || NULL == head->next)
{
return head;
}
ListNode* oddTail = NULL;
ListNode* evenHead = head->next;
ListNode* odd = head;
ListNode* even = head->next;
while(even && odd)
{
if(even)//偶数结点不空,设置奇数结点
{
oddTail = odd;
odd->next= even->next;//设置奇数结点指针指向
odd = odd->next;//移动奇数结点指针
}
if(odd)//奇数
{
even->next = odd->next;
even = even->next;
}
}
//设置奇数结点链表尾部指向偶数结点链表头部
if(odd)
{
odd->next = evenHead;
}
else
{
oddTail->next = evenHead;
}
return head;
}
};
void print(ListNode* head)
{
if(!head)
{
cout << "no result" << endl;
}
ListNode* tempHead = head;
while(head)
{
cout << head->val << " ";
head = head->next;
}
cout << endl;
head = tempHead;
}
ListNode* buildList(vector<int>& nums)
{
if(nums.empty())
{
return NULL;
}
int size = nums.size();
ListNode* head ;
ListNode *tail;
ListNode* node;
for(int i = 0 ; i < size ; i++)
{
if(i)
{
node = new ListNode(nums.at(i));
tail->next = node;
tail = node;
}
else
{
head = new ListNode(nums.at(i));
tail = head;
}
}
return head;
}
void deleteList(ListNode* head)
{
ListNode* node;
while(head)
{
node = head->next;
delete head;
head = node;
}
}
void process()
{
vector<int> nums;
int value;
int num;
Solution solution;
vector<int> result;
while(cin >> num )
{
nums.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
nums.push_back(value);
}
ListNode* head = buildList(nums);
ListNode* newHead = solution.oddEvenList(head);
print(newHead);
deleteList(newHead);//删除节点了
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:328. Odd Even Linked List
最新推荐文章于 2019-11-21 08:16:16 发布