重新排列链表以使距起点和终点相同距离的节点异或
给定一个包含N个二进制数节点的链表,任务是检查是否可以重新排列链表,使得第 i 个节点的元素之间的XOR值 并且N+1−ith节点对于所有1 ≤ i ≤ N都是相同的。如果可以重新排列链接列表,则打印Yes ,否则打印No 。
例子:
Input: LL = 0 -> 0 -> 1
Output: Yes
Explanation : 001 can be rearranged to form 010 which means 0 ⊕ 0 = 0 and 1 ⊕ 1 =0 are same . So output is 1.
Input : 0001 (0->0->0->1)
Output : No
Explanation : 0001 can not be rearranged . So output is 0.
方法:该思想基于链表遍历,基于以下观察:
Case 1: If size of linked linked list is odd, then it is always possible. So directly return Yes.
For example:
- 00001 can be rearranged as 00100
- 00011 can be rearranged as 10001
- 00111 can be rearranged as 10101
- 01111 can be rearranged as 11011
Case 2: If size of linked linked list is even, Count the number of 1 present in linked list. If number of 1s present in linked list is equal to the half the size of linked list, then return Yes, because rearrangement will be always possible.
For example:
- 0011
number of 1’s = half of size of linked list
so it can be rearranged as 1001 - 001101
number of 1’s = half of size of linked list
so it can be rearranged as 010101
Case 3: if number of 1’s present in our linked list is even, then also it is always possible. So directly return Yes.
For example:
- 000011 can be rearranged as 100001 or 001100
- 011 can be rearranged as 101
Case 4: if above all conditions are false, then return No.
For example:
- 011111 cannot be rearranged
- 000001 cannot be rearranged
按照以下步骤实施上述方法:
- 计算链表的大小。
- 如果大小是奇数,则返回 1,因为总是可以重新排列链表,如上所述。
- 如果 size 是偶数,则计算节点组成值 1 的数量。
- 如果节点数组成值 1 是链表大小的一半,则返回 1。
- 如果大小为偶数且节点数组成值 1 为偶数,则返回 1。
- 如果上述所有条件都未能执行,则返回 0。
下面是上述方法的实现:
C++
// C++ code for the above approach:
#include
using namespace std;
// Node Class
class Node {
public:
int data;
Node* next;
};
// Function to append the node
void append(Node** head_ref, int new_data)
{
Node* new_node = new Node();
Node* last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
return;
}
// Count the size of linked list
int CountSize(Node* head)
{
Node* temp = head;
int count = 0;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
// Bool function to check
// is it possible to make
// such linked list
bool isPossible(Node* head)
{
// count size of linked list
int n = CountSize(head);
// if n is odd
if (n % 2 != 0) {
return 1;
}
else {
int o = 0;
Node* temp = head;
while (temp != NULL) {
if (temp->data == 1) {
o++;
}
temp = temp->next;
}
if (o == (n / 2)) {
return 1;
}
else if (o % 2 == 0) {
return 1;
}
else {
return 0;
}
}
}
// Driver Code
int main()
{
Node* head = NULL;
append(&head, 0);
append(&head, 0);
append(&head, 1);
append(&head, 1);
cout << (isPossible(head) == 1
? "Yes"
: "No")
<< endl;
}
Javascript
Yes
时间复杂度: O(N)
辅助空间: O(1)