stack-- 基于双向链表实现(java实现)--基于数组实现(c实现)
1 //不考虑任何情况的判断
package cn.it.struct; 2 3 public class MyStack<T> { 4 private int top=-1; 5 6 private Node<T> current; 7 8 9 private class Node<T>{ 10 private T data; 11 12 private Node<T> next; 13 14 private Node<T> pre; 15 16 } 17 18 //初始化 19 public MyStack(){ 20 top = -1; 21 current = new Node<T>(); 22 } 23 24 //压Stack 25 public boolean push(T data){ 26 Node<T> node = new Node<T>(); 27 node.data = data; 28 current.next = node; 29 current = node.pre; 30 current = node; 31 top++; 32 return false; 33 } 34 35 //出Stack 36 public T poll(){ 37 T data = current.data; 38 current = current.pre; 39 top--; 40 return data; 41 } 42 }
1 #include<stdlib.h> 2 /* 3 * 4 * 基于arraylist实现 5 * 6 * */ 7 #define STACK_INIT_SIZE 100 8 9 typedef char ele; 10 11 typedef struct { 12 ele *top; 13 ele *base; 14 int len; 15 }stack; 16 17 //初始化 18 void init(stack *s){ 19 s->base=(ele *)malloc(STACK_INIT_SIZE*sizeof(ele)); 20 if(!s->base)exit(0); 21 s->top=s->base; 22 s->len=STACK_INIT_SIZE; 23 } 24 25 //插入 26 void push(stack *s,ele e){ 27 if(s->top-s->base>=s->len){ 28 s->base=realloc(s->base, s->len + 10 *sizeof(ele)); 29 if(!s->base){ 30 exit(0); 31 } 32 *(s->base+s->len+1)=e; 33 s->len=10+s->len; 34 }else{ 35 *(s->base+s->len)=e; 36 } 37 *(s->top)=e; 38 } 39 40 //pop 41 ele pop(stack *s){ 42 if(*(s->top)==*(s->base)){return NULL;} 43 (s->base+s->len-1)=NULL; 44 s->len--; 45 return *(s->top); 46 }