链式堆栈(C,JAVA分别实现)

来源:互联网 发布:nokia软件下载 编辑:程序博客网 时间:2024/05/19 07:07

先附上,C语言。

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <malloc.h>struct Node {int date;struct Node *next;};void Init(Node *s){s->date = 0;s->next = NULL;}void Push(Node *s){Node *p = NULL;p = (Node *)malloc(sizeof(Node));scanf("%d", &p->date);p->next = s->next;s->next = p;}void Pop(Node *s){Node *p = NULL;p = s->next;printf("%d ", p->date);s->next = p->next;free(p);}void Destroy(Node *s){Node *p = NULL, *q = NULL;p = s;while (p != NULL){q = p;p = p->next;free(q);}}int main(){int n;Node s;Init(&s);printf("请输入入栈的数据个数:");scanf("%d", &n);for (int i = 0; i < n; i++)Push(&s);for (int i = 0; i < n; i++)Pop(&s);return 0;}

JAVA

package test01;public class StackNode{private int date;private StackNode next;StackNode(){date = 0;next = null;}    public void clear(){    StackNode p = null, q = null;    p = this.next;       while(p.next != null){       q = p;       p = p.next;     q.date = 0;       q.next = null;    }    }        public int length(){    int len = 1;    if(this.empty())    return 0;    else{    StackNode p;    p = this.next;    while(p.next != null){    len++;    p = p.next;    }    }    return len;    }public boolean full(){return false;}        public boolean empty(){    if(next == null)    return true;    else    return false;    }        public void push(int item){    StackNode p = new StackNode();    p.date = item;    p.next = this.next;    this.next = p;    }    int pop(){    StackNode p = null, q = null;    p = this.next;    q = p;    this.next = p.next;    return q.date;    }    public int peek(){    return this.next.date;    }        public static void main(String[] args){StackNode s = new StackNode();for(int i = 0; i < 10; i++)s.push(i + 1);int len = s.length();System.out.println("len = "+len);System.out.print("Output:");for(int i = 0; i < 10; i++){int date = s.pop();System.out.print(date+" ");}System.out.println();    }}



0 0
原创粉丝点击