將連結串列中的第一個元素移至末尾,使用 C++


<

給定一個連結串列,我們要將第一個元素移至末尾。我們來看一個示例。

輸入

1 -> 2 -> 3 -> 4 -> 5 -> NULL

輸出

2 -> 3 -> 4 -> 5 -> 1 -> NULL

演算法

  • 初始化連結串列。

  • 如果連結串列為空或僅含一個節點,則返回。
  • 查詢連結串列的最後一個節點。

  • 將第二個節點設定為新開頭。

  • 更新第一個和最後一個節點的連結。

實現

以下是上述演算法在 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* firstNode = *head;
   struct Node* lastNode = *head;
   while (lastNode->next != NULL) {
      lastNode = lastNode->next;
   }
   *head = firstNode->next;
   firstNode->next = NULL;
   lastNode->next = firstNode;
}
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;
}

輸出

如果你執行以上程式碼,則會得到以下結果。

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

更新時間: 2021 年 10 月 25 日

482 次瀏覽

開啟你的 職業生涯

獲得課程認證

開始
廣告