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

先附上,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();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值