【发布时间】:2020-03-31 19:04:38
【问题描述】:
我必须按照低 -> 高 -> 低 -> 高 -> 低的模式订购给定的链接列表 1 -> 2 -> 3 -> 4 -> 5 导致 1 -> 3 -> 2 - > 5 -> 4.
我已经编码了这个:
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
node* getHead()
{
return head;
}
};
int main()
{
linked_list a;
a.add_node(1);
a.add_node(2);
a.add_node(3);
a.add_node(4);
a.add_node(5);
bool leave= false;
int direction = 1;
node* considered_node = new node(*(a.getHead()));
while(true)
{
if (considered_node->next == NULL)
{
break;
}
else if (direction*considered_node->next->data < direction*considered_node->data)
{
int t= direction*considered_node->next->data;
int p = direction*considered_node->data;
int tmp = considered_node->next->data;
considered_node->next->data = considered_node->data;
considered_node->data = tmp;
}
delete considered_node;
considered_node = considered_node->next;
direction = -1*direction;
}
return 0;
}
但是我在迭代链接列表并删除指针以避免内存泄漏的方式上犯了一个错误。我不想只更改 for 循环的链接列表的声明。
【问题讨论】:
-
delete considered_node; considered_node = considered_node->next;是未定义行为,因为您在删除后访问内存。 -
不是必需的,但无论如何应该只是一对一的比较,所以你应该最多将每个元素移动 1 个位置。所以我希望它可以生成任何订单
-
在 for 循环之后移动你的
delete considered_node;。 -
在完成for循环后删除
considered_node之前还要添加considered_node->next->data = considered_node->data;。 -
顺便说一句,这是一个“链接”列表
标签: c++ class linked-list swap singly-linked-list