Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Subject description:
Given a single list, all the nodes of the odd and even rows, respectively, with the node. Note that, here node odd and even parity node refers to a node number, rather than the value of the parity nodes.
Try using in-place algorithm is complete. Space complexity of your algorithm should be O (1), time complexity should total number of nodes is O (nodes), nodes.
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
Description:
The relative order of the odd and even number of nodes of the nodes should be kept.
The list of the first node considered odd node, the second node as an even number of nodes, and so on.
#include <vector>
#include <stdio.h>
#include <algorithm>
using namespace std;
#include <iostream>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *createLinkedList(int nums[], int len_nums)
{
if (len_nums == 0)
{
return NULL;
}
ListNode *head = new ListNode(nums[0]);
ListNode *curNode = head;
int i = 1;
while (i < len_nums)
{
ListNode *nextNode = new ListNode(nums[i]);
curNode->next = nextNode;
curNode = nextNode;
i++;
}
curNode->next = NULL;
return head;
}
void printLinkedList(ListNode *head)
{
ListNode *curNode = head;
while (curNode != NULL)
{
printf("%d -> ", curNode->val);
curNode = curNode->next;
}
printf("NULL\n");
}
class Solution
{
public:
ListNode *oddEvenList(ListNode *head)
{
if (head == NULL)
{
return NULL;
}
int index = 1;
ListNode *curNode = NULL;
ListNode *cur2Node = NULL;
ListNode *preNode = NULL;
ListNode *nextNode = head;
while (nextNode != NULL)
{
if (index % 2 == 0)
{
if (!cur2Node)
{
cur2Node = nextNode;
}
else
{
preNode->next = nextNode;
preNode = nextNode;
}
preNode = nextNode;
nextNode = nextNode->next;
index++;
}
else
{
if (!curNode)
{
curNode = nextNode;
}
else
{
curNode->next = nextNode;
curNode = nextNode;
}
nextNode = nextNode->next;
index++;
}
}
curNode->next = cur2Node;
if (preNode != NULL)
{
preNode->next = NULL;
}
return head;
}
};
int main()
{
int nums[] = {1};
int len_nums = sizeof(nums) / sizeof(int);
ListNode *head = createLinkedList(nums, len_nums);
printLinkedList(head);
ListNode *ans = Solution().oddEvenList(head);
printLinkedList(ans);
return 0;
}