📅  最后修改于: 2023-12-03 15:29:53.045000             🧑  作者: Mango
这个C++程序的主要功能是在链表中交换第K个节点和第n-k+1个节点。它是一个链表工具,可以在链表中使用它。
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
Node *pre,*p;
void reverseK(Node** head, int k)
{
Node* with = *head;
Node* without = *head;
Node* before = NULL;
Node* after = NULL;
int i = 1;
//找到第k个节点
while (with != NULL && i < k)
{
before = with;
with = with->next;
i++;
}
//找到第n-k+1个节点
while (without != NULL && i > 0)
{
after = without;
without = without->next;
i--;
}
//交换节点
pre->next = with;
p = with->next;
with->next = without->next;
after->next = p;
without->next = pre->next;
}
void push(Node** head, int new_data)
{
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head);
(*head) = new_node;
}
void printList(Node* node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
int main()
{
Node* head = NULL;
for (int i = 10; i > 0; i--)
push(&head, i);
printf("Original Linked list: ");
printList(head);
int k = 6;
reverseK(&head, k);
printf("\nModified Linked list: ");
printList(head);
return 0;
}
该程序使用了指针来完成链表中第K个节点和第n-k+1个节点的交换。程序的主要部分是reverseK
函数,它在链表中找到第K个和第n-k+1个节点,然后交换它们。
另一个函数push
用于在链表的开头添加一个节点。
printList
函数用于打印链表。
主函数用于创建链表并调用reverseK
函数。
输入:k = 6
输出:
Original Linked list: 1 2 3 4 5 6 7 8 9 10
Modified Linked list: 1 2 3 4 5 9 7 8 6 10