Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

마지막 요소를 C++에서 주어진 연결 목록 앞으로 이동

<시간/>

연결된 목록이 주어지면 마지막 요소를 앞으로 이동해야 합니다. 예를 들어 보겠습니다.

입력

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

출력

5 -> 1 -> 2 -> 3 -> 4 -> 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* 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