赞
踩
栈--先进后出
所以压栈时我们采用头插法,这样一来头部指针便是栈顶。
出栈直接出头结点即可。
- package com.Execise;
-
- /**
- * @Author:XK
- * @Date: Created in 16:11 2022/1/16
- * @Description:
- **/
- public class NodeStackDemo {
- private Node header;//栈顶
- private int elementCount;//元素个数
- private int size;//栈大小
- public NodeStackDemo(){
- header=null;
- elementCount=0;
- size=10;
- }
- public void push(int x){
- if(elementCount==10){
- System.out.println("stack is full!");
- return;
- }else if(elementCount==0){
- header=new Node();
- header.value=x;
- elementCount++;
- }else {
- Node node = new Node();
- node.value=x;
- node.next=header;
- header=node;
- elementCount++;
- }
- }
-
- public int pop(){
- if(elementCount==0){
- System.out.println("stack is empty!");
- return 0;
- }else{
- int i=header.value;
- header=header.next;
- elementCount--;
- return i;
- }
- }
-
- public static void main(String[] args) {
- NodeStackDemo nodeStackDemo = new NodeStackDemo();
- nodeStackDemo.push(1);
- nodeStackDemo.push(2);
- nodeStackDemo.push(3);
- nodeStackDemo.push(3);
- nodeStackDemo.push(3);
- System.out.println(nodeStackDemo.header);
- nodeStackDemo.pop();
- nodeStackDemo.pop();
- System.out.println(nodeStackDemo.header);
- }
-
- }
3->3->3->2->1->null
3->2->1->null
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。