c++ - C++ 程序,它以这样一种方式分隔链表中的节点,使得所有偶数节点都出现在链表的开头
问题描述
谁能解释我这段代码。它运行完美,但我不明白如何:(。我已经通过为链表的节点创建一个结构来解决这个问题。然后是两个函数,一个用于在链表的开头插入和一个显示链表。
可以请解释无效的隔离功能。
#include <bits/stdc++.h>
using namespace std;
struct LLNode
{
int data;
struct LLNode* next;
};
void insertAtBeginning(struct LLNode** head, int dataToBeInserted)
{
struct LLNode* current = new LLNode;
current->data = dataToBeInserted;
current->next = NULL;
if(*head == NULL)
*head=current;
else
{
current->next=*head;
*head=current;
}
}
void display(struct LLNode**node)
{
struct LLNode *temp= *node;
while(temp!=NULL)
{
if(temp->next!=NULL)
cout<<temp->data<<" --> ";
else
cout<<temp->data;
temp=temp->next;
}
cout<<endl;
}
void Segregate(struct LLNode **head)
{
struct LLNode *end = *head;
struct LLNode *previous = NULL;
struct LLNode *current = *head;
while (end->next != NULL)
{
end = end->next;
}
struct LLNode *new_end = end;
while(current->data % 2 != 0 && current != end)
{
new_end->next = current;
current = current->next;
new_end->next->next = NULL;
new_end = new_end->next;
}
if(current->data%2 == 0)
{
*head = current;
while(current!= end)
{
if((current->data)%2 == 0)
{
previous = current;
current = current->next;
}
else
{
previous->next = current->next;
current->next = NULL;
new_end->next = current;
new_end = current;
current = previous->next;
}
}
}
else previous = current;
if (new_end!=end && (end->data)%2 != 0)
{
previous->next = end->next;
end->next = NULL;
new_end->next = end;
}
return;
}
int main()
{
struct LLNode* head = NULL;
insertAtBeginning(&head, 341);
insertAtBeginning(&head, 362);
insertAtBeginning(&head, 921);
insertAtBeginning(&head, 748);
insertAtBeginning(&head, 210);
insertAtBeginning(&head, 701);
insertAtBeginning(&head, 300);
insertAtBeginning(&head, 899);
insertAtBeginning(&head, 407);
insertAtBeginning(&head, 666);
insertAtBeginning(&head, 369);
insertAtBeginning(&head, 235);
insertAtBeginning(&head, 236);
cout<<endl;
cout<<endl;
cout<<"The Input linked list is: "<<endl;
display(&head);
Segregate(&head);
cout<<endl;
cout<<endl;
cout<<"The Final Modified linked list in such a way that all the even nodes appear at the begining of the Linked List is: "<<endl;
display(&head);
cout<<endl;
cout<<endl;
return 0;
}
解决方案
- while(current->data % 2 != 0 && current != end) 在这个while循环中,从第一个节点开始,所有奇数节点都被移动到最后,直到到达终点或找到偶数节点(偶数节点) .
- 下一个 if(current->data%2 == 0) 否则上一个 = 当前;处理直到最后一个节点的所有元素。在 while(current!= end) 中,所有奇数元素都移动到 end。
- if (new_end!=end && (end->data)%2 != 0) 处理最后一个节点,如果是奇数,则移动到链表的末尾。
必须说,代码可以大大简化。
推荐阅读
- javascript - 如何从数组中删除对象?
- haskell - 为什么“<-”的这种用法会导致正确计算幂集?
- scala - 对数据框进行分区,以便为每个类标签提供最少的数据量(分层分区)
- discord - 我想为我的不和谐机器人设置一个自定义状态(又名“正在播放 | $help for commands”)
- python - 'builtin_function_or_method' 对象对于带有 i 的 while 循环不可下标
- javascript - 如何使用验证此格式的外部 JS 文件创建 html 页面 AAA.111#2222_aa-1234
- python - 将全连接层转换为卷积层时出错
- python - 如何使用 Discord.py 向特定频道发送消息?
- python - 为什么非线程程序执行速度比线程程序在 python 中下载数据集的速度快
- reactjs - 反应函数参数 - 失败的道具类型:预期的“布尔”