打印使用堆栈反向链接列表
给定一个链接列表,程序必须使用堆栈数据结构从末端打印到前端的列表
Input : 10 -> 5 -> 3 -> 1 -> 7 -> 9 Output: 9 -> 7 -> 1 -> 3 -> 5 -> 10
在这里,用户可以使用弹栈元素的方法,从堆栈[0] 位置的堆栈顶开始,然后一直到堆栈[n] 元素
算法
START Step 1 -> create structure Linked_list Declare int data Declare struct linked_list *next End Step 2 -> declare int stack[30], top = -1 Step 3 -> declare struct linked_list* head = NULL Step 4 -> create function int printfromstack(int stack[]) Loop While top>=0 Print stack[--top] End Step 5 -> create function int push(struct linked_list** head, int n) declare struct linked_list* newnode = (struct linked_list*)malloc(sizeof(struct linked_list)) set newnode->data = n set newnode->next = (*head) set (*head) = newnode step 6 -> create function int intostack(struct linked_list* head) Loop While head!=NULL Print head->data Set stack[++top] = head->data Set head = head->next End End Step 7 -> goto main() Call push(&head, 10) Call push(&head, 20) Call push(&head, 30) Call push(&head, 40) Call intostack(head) Call printfromstack(stack) STOP
示例
#include <stdio.h>
#include <stdlib.h>
struct linked_list {
int data;
struct linked_list *next;
};
int stack[30], top = -1;
struct linked_list* head = NULL;
int printfromstack(int stack[]) {
printf("
Stack:
");
while(top>=0) {
printf("%d ", 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) {
printf("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, 10);
push(&head, 20);
push(&head, 30);
push(&head, 40);
intostack(head);
printfromstack(stack);
return 0;
}输出
如果运行上述程序,它将生成以下输出
Linked list: 40 30 20 10 Stack: 10 20 30 40
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP