切换链表中的两个节点
switching two nodes in a linked list
我对编程相当陌生,我有这个任务,目标是打印出0123456789然后使用这些函数9876543210
bool List::SortSwap()
{
bool doswap = true;
ListElement *i =this-> head;
ListElement *prev =this-> head;
ListElement *b = i->next;
while (doswap= true) {
for (i; i != NULL; i = i->next) {
if (i != this-> head) {
prev->next = i;
}
if (i->value < b->value) {
swap(prev, i, b);
doswap = true;
}
}
doswap= false;
}
return doswap;
}
void List::swap(ListElement * prev, ListElement * a, ListElement * b)
{
prev->next = b;
b->next = a;
}
因此,如果 doswap 为真,它应该通过我的链表并交换元素,如果它的值小于后面的值,当我运行程序时没有任何反应,我的列表不会打印到屏幕上
如果b
是a
的继承者并且a
prev
的继承者,那么你必须将b
作为prev
的继承者,a
作为b
的继承者,交换a
和b
:
void List::swap( ListElement * prev, ListElement * a, ListElement * b)
{
a->next = b->next; // put successor of b in place of succesor of a
b->next = a; // put a in place of successor of b
prev->next = b; // put b in place of succesor of prev
}
要按顺序交换列表的元素,您必须处理列表的前两个元素。所以列表的其余部分一步一步。如果到达最后一个列表元素的前置项,则终止。
bool List::SortSwap()
{
if ( head == nullptr || head->next == nullptr )
return false;
bool anySwapped = false;
// hadle head of list and its successor
if ( head->value < head->next->value )
{
ListElement *temp = head;
head = head->next; // successor of head becomes new head
temp->next = head->next; // successor of old head becomes successor of new head
head->next = temp; // new head becomes succesor of old head
anySwapped = true;
}
// continue until predecessor of tail is found
ListElement *prev = head;
while ( prev->next != nullptr && prev->next->next != nullptr )
{
ListElement *a = prev->next;
ListElement *b = a->next;
if ( a->value < b->value )
{
swap( prev, a, b );
anySwapped = true;
}
prev = prev->next; // step one forward
}
return anySwapped;
}
请注意,(doswap= true)
是一项分配。循环while (doswap= true)
是无限的。
假设这是节点当前排列的方式,在交换之前:
prev --> a --> b
此外,假设这是交换后节点应该的样子:
prev --> b --> a
如果以上是交换应该更改的内容,则代码在您的交换函数中需要保存节点"B"作为其下一个节点指针:
void List::swap(ListElement * prev, ListElement * a, ListElement * b)
{
ListElement * temp = b->next;
prev->next = b;
b->next = a;
a->next = temp;
}
所以你要做的是反转列表我做过这样的事情。
void LinkList::ReverseList()
{
int Length=0;
current=Head;
while (current!=NULL)
{
current=current->link;
Length++;
}
cout<<"Length is:"<<Length<<endl;
Prev=current=Head;
Temp=Head;
Temp=Temp->link;
for (int i= 0; i<Length-1; i++)
{
if (i==0)
{
Prev=Temp;
current->link=NULL;
Temp=Temp->link;
Prev->link=current;
current=Prev;
}
else
{
Prev=Temp;
if (Temp->link!=NULL)
{
Temp=Temp->link;
}
Prev->link=current;
current=Prev;
}
}
Head=current;
}
相关文章:
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 比较两个节点坐标的最佳方法是什么?
- 使用 Dijkstra 算法跟踪两个节点之间的最短路径
- 图问题:找出两个节点是否在每个节点的O(1)时间和O(2)存储中共享同一分支
- 如何在单个链表中交换两个节点的位置,只修改指针
- 如何遍历具有两个节点的链接节点
- 查找树中两个节点之间的最大成本边
- 查找树(不属于任何特定类型的简单连接树)中两个节点之间的路径
- 为什么不交换两个节点?
- 使用 Dijkstra 算法计算两个节点之间的最短路径
- 在 C 语言的链表中查找最小的两个节点
- 当两个节点相互指向时,不可避免的内存泄漏
- 如何使用BFS查找两个节点之间的距离
- 添加两个节点并在比较时删除一个节点
- 如何在C++中合并二叉树的两个节点
- 树中两个节点之间的最小距离
- 反转两个节点之间的链表
- 切换链表中的两个节点
- 查找树中两个节点的最小共同祖先