仅通过操作指针交换链表中的相邻节点
Swap Adjacent nodes in a Linked List Only by Manipulating pointers
我正在尝试交换链表的相邻节点,即
1->2->3->4->5变成2->1->4->3->5
我的功能是:
node * swapper(node * &head)
{
if (head == NULL || head->next == NULL) return head;
node * t = head;
head= head->next;
head->next = t;
t->next = head->next;
node *previous = head->next->next, *current = previous->next;
while (current!=NULL&&previous!=NULL)
{
node * t1 = current,*t2=previous;
current->next = previous;
previous->next = t1->next;
previous = t1->next;
current = previous->next;
}
return head;
}
我知道它可以通过交换值来实现,但我必须在常量空间中进行操作,并且不能交换值。
我不知道为什么我的函数不工作
我注意到的第一件事是您需要交换这两行:
head->next = t;
t->next = head->next;
因为你说了head->next = t,所以你失去了与链表其余部分的连接。
同样,在循环内部。这里有几个错误:1-你在之前获得它之前改变了下一个电流,这意味着你失去了链接(如上所述)2-你没有将它们连接到它们之前的节点
我的五分钱。
下面是一个演示程序,演示如何编写递归函数。
#include <iostream>
#include <functional>
struct node
{
int data;
struct node *next;
} *head;
void push_front( node * &head, int x )
{
head = new node { x, head };
}
void display( node *head )
{
for ( node *current = head; current; current = current->next )
{
std::cout << current->data << ' ';
}
std::cout << std::endl;
}
node * swapper( node * &head )
{
if ( head && head->next )
{
node *tmp = std::exchange(head, head->next );
std::exchange( tmp->next, std::exchange( tmp->next->next, tmp ) );
swapper( head->next->next );
}
return head;
}
int main()
{
const int N = 10;
for ( int i = N; i != 0; ) push_front( head, --i );
display( head );
display( swapper( head ) );
}
程序输出如下
0 1 2 3 4 5 6 7 8 9
1 0 3 2 5 4 7 6 9 8
请注意并非所有编译器都支持函数std::exchange
。所以你需要自己写:)
如果按照下面的方式写main
int main()
{
const int N = 10;
for ( int i = N; i != 0; ) push_front( head, --i );
display( head );
for ( node **current = &head; *current && ( *current )->next; current = &( *current )->next )
{
swapper( *current );
}
display( head );
}
,则可以得到以下有趣的输出::)
0 1 2 3 4 5 6 7 8 9
1 3 5 7 9 8 6 4 2 0
node * swapper(node * &head)
{
if (head == NULL || head->next == NULL) return head;
node * t = head;
head= head->next;
t->next = head->next;
head->next = t;
node *previous = head->next->next, *current,*parent=head->next;
while (previous&&(current = previous->next))
{
node * t1 = current,*t2=previous;
previous->next = t1->next;
current->next = previous;
parent->next= current;
previous = t2->next;
//current = previous->next;
parent=t2;
}
return head;
}
相关文章:
- 反向给定链表中的K节点
- 我们可以删除链表中静态内存中的节点吗
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 如何按数字顺序插入链表节点?
- 为什么我的双向链表删除函数会删除多个节点?
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 在C++的链表末尾插入一个节点
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 插入一个基本的单向链表节点似乎破坏了我的 c++ 代码?
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 删除链表中的特定节点
- 在 c++ 中,在链表节点上使用括号有什么意义?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 删除链表中的节点 - 分段错误
- 使用函数引用指向节点的指针删除链表中的节点?
- 节点链表中的对象
- 虚拟头节点链表
- C++ 删除类似的节点链表
- c++删除节点链表导致程序崩溃
- 排序节点(链表)c++