在 C++ 中将最后一个元素移动到给定链表的前面

在本教程中,我们将编写一个程序,将最后一个元素移动到给定链表的前面。

让我们看看解决问题的步骤。

  • 初始化链表。

  • 找到链表的最后一个节点和倒数第二个节点。

  • 将最后一个节点作为新头。

  • 更新倒数第二个节点的链接。

示例

让我们看看代码。

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void moveFirstNodeToEnd(struct Node** head) {
   if (*head == NULL || (*head)->next == NULL) {
      return;
   }
   struct Node* secondLastNode = *head;
   struct Node* lastNode = *head;
   while (lastNode->next != NULL) {
      secondLastNode = lastNode;
      lastNode = lastNode->next;
   }
   secondLastNode->next = NULL;
   lastNode->next = *head;
   *head = lastNode;
}
void addNewNode(struct Node** head, int new_data) {
   struct Node* newNode = new Node;
   newNode->data = new_data;
   newNode->next = *head;
   *head = newNode;
}
void printLinkedList(struct Node* node) {
   while (node != NULL) {
      cout << node->data << "->";
      node = node->next;
   }
   cout << "NULL" << endl;
}
int main() {
   struct Node* head = NULL;
   addNewNode(&head, 1);
   addNewNode(&head, 2);
   addNewNode(&head, 3);
   addNewNode(&head, 4);
   addNewNode(&head, 5);
   addNewNode(&head, 6);
   addNewNode(&head, 7);
   addNewNode(&head, 8);
   addNewNode(&head, 9);
   moveFirstNodeToEnd(&head);
   printLinkedList(head);
   return 0;
}
输出结果

如果你运行上面的代码,那么你会得到下面的结果。

1->9->8->7->6->5->4->3->2->NULL

结论

如果您对本教程有任何疑问,请在评论部分提及。