链表动态分配内存,用于实现堆栈。该程序展示了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()方法中,随后该调用被传递给程序main()执行。
输出结果
Linked list:: 40 3 20 7 Stack after Reversal::7 20 3 40