使用 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
基於上述演算法,起草了以下 c++ 程式碼,其中stdlib 庫檔案發揮了關鍵作用,提供瞭如下堆疊相關關鍵方法;
示例
#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() 方法中,之後,該呼叫被傳遞給程式主() 執行。
輸出
Linked list:: 40 3 20 7 Stack after Reversal::7 20 3 40
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP