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

C++에서 스택을 사용하여 링크 목록 반전

<시간/>

연결 목록은 메모리를 동적으로 할당하며 스택을 구현하는 데 사용됩니다. 이 프로그램은 C++ 프로그래밍에서 링크 목록의 반전을 보여줍니다. 여기에서 지망자는 다음과 같은 접근 방식을 채택하여 예상 결과를 얻을 수 있습니다. 알고리즘은 다음과 같습니다.

알고리즘

START
   Step 1: create an empty stack of type node pointer
   Step 2: Traverse the list and push all of its nodes onto a stack
   Step 4: Traverse the list from the head node again
   Step 5: pop a value from the stack top
   step 6: connect them in reverse order
   Step 7: PRINT
STOP

위의 알고리즘을 기반으로 stdlib 위치에 다음 C++ 코드가 작성됩니다. 라이브러리 파일 에세이 핵심 역할은 다음과 같은 스택 관련 핵심 방법을 사용합니다.

#include <iostream>
#include <stdlib.h>
using namespace std;
struct linked_list {
   int data;
   struct linked_list *next;
};
int stack[30], top = -1;
struct linked_list* head = NULL;
int printfromstack(int stack[]) {
   cout<<"\nStack after Reversal::";
   while(top>=0) {
      cout<<stack[top--]<<" ";
   }
}
int push(struct linked_list** head, int n) {
   struct linked_list* newnode = (struct linked_list*)malloc(sizeof(struct linked_list));
   newnode->data = n;
   newnode->next = (*head);
   (*head) = newnode;
}
int intostack(struct linked_list* head) {
   cout<<"Linked list::";
   while(head!=NULL) {
      printf("%d ", head->data);
      stack[++top] = head->data;
      head = head->next;
   }
}
int main(int argc, char const *argv[]) {
   push(&head, 7);
   push(&head, 20);
   push(&head, 3);
   push(&head, 40);
   intostack(head);
   printfromstack(stack);
   return 0;
}

위 코드에서 볼 수 있듯이 모든 문자열 연산 코드는 retrieveChar() 메소드, 나중에 프로그램 main() 실행에 전달되는 호출.

출력

Linked list:: 40 3 20 7
Stack after Reversal::7 20 3 40