栈实现

来源:互联网 发布:淘宝虚拟物品拒绝退款 编辑:程序博客网 时间:2024/05/16 15:43

#include<stdio.h>

class node
{
public:
 int data;
 node *plink;
};
class List
{
public:
 node *head;
public:
 List()
 {
  head = NULL;
 }
 ~List()
 {
  node *temp;
  while(head)
  {
   temp = head->plink;
   delete head;
   head = temp;
  }
 }
 bool Insert(int k, int e)
 {
        node *temp;
  temp = head;
  for(int i=1; (i<k)&&temp; i++)
   temp = temp->plink;

  node *new_node = new node;
  new_node->data = e;
  if(k)
  {
   new_node->plink = temp->plink;
   temp->plink = new_node;
  }
  else
  {
   new_node->plink = head;
   head = new_node;
  }

  return true;

 }
 bool Delete(int k)
 {
  if(k == 1)
  {
   head = head->plink;
   return true;
  }

  node *temp;
  temp = head;
  for(int i=1; (i<(k-1))&&temp; i++)
   temp = temp->plink;

  node *tempDel;
  tempDel = temp->plink;
        temp->plink = tempDel->plink;

  return true;

 }
 int get(int k)
 {
  node *temp;
  temp = head;
  for(int i=1; (i<k)&&temp; i++)
   temp = temp->plink;

  return temp->data;
 }
 int Length()
 {
  int length = 0;
  node *temp;
  temp = head;
  while(temp)
  {
   length++;
   temp = temp->plink;
  }
  return length;
 }
 bool IsEmpty()
 {
  return head==NULL;
 }
};
class Stack:public List
{
public:
 
 Stack(){}
 ~Stack(){}
 Push(int e)
 {
  Insert(Length(), e);
 }
 Pop()
 {
  Delete(Length());
 }
 int GetTop()
 {
  return get(Length());
 }

};
int main()
{
    Stack stack;
 stack.Push(1);
 stack.Push(2);
 stack.Push(2);
 stack.Push(2);
 stack.Push(3);

 while(1)
 {
  printf("%d/n", stack.GetTop());
  stack.Pop();
  if(stack.IsEmpty())
   break;
 }
}

原创粉丝点击