顺序栈和链栈实现汉洛塔

来源:互联网 发布:内容管理cms 编辑:程序博客网 时间:2024/06/01 10:48

顺序栈:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#define STACKSIZE 10

typedef struct stack
{
 int data[STACKSIZE];
 int top;
}stack;

bool isempty(stack *ps)
{
 return ps->top == -1;
}

void push(int num, stack *ps)
{
 (ps->top)++;
 (ps->data)[ps->top] = num;
}

int pop(stack *ps)
{
 if(!isempty(ps)){
  int ret = (ps->data)[ps->top];
  (ps->data)[ps->top] = 0;
  ps->top--;
  return ret;
 }
 else
  return 0;
}

void show(int hanois, stack *ps1, stack *ps2, stack *ps3)
{
 int i;
 for(i=0; i<hanois; i++){
  printf("%d/t%d/t%d/n", (ps1->data)[hanois-i-1],
   (ps2->data)[hanois-i-1], (ps3->data)[hanois-i-1]);
 }
 printf("-----------------/n");
}

void towers_of_hanoi(int hanois, stack *ps1, stack *ps2, stack *ps3)
{
 int tmp;
 if(hanois > 0){
  towers_of_hanoi(hanois-1, ps1, ps3, ps2);

  tmp = pop(ps1);
  push(tmp, ps2);

  towers_of_hanoi(hanois-1, ps3, ps2, ps1);
 }
}

void init(stack *ps, int hanois)
{
 int i;
 ps->top = -1;

 for(i=0; i<hanois; i++){
  push(hanois-i, ps);
 }
}

int main(void)
{
 printf("how many hanois ? ");
 int hanois;
 scanf("%d", &hanois);

 if(hanois > STACKSIZE){
  printf("too big/n");
  return 0;
 }

 static stack s1, s2, s3;

 init(&s1, hanois);
 init(&s2, 0);
 init(&s2, 0);

 show(hanois, &s1, &s2, &s3);
 towers_of_hanoi(hanois, &s1, &s2, &s3);
 show(hanois, &s1, &s2, &s3);

 return 0;
}

 

链栈实现:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

typedef struct stack
{
 int data;
 struct stack *next;
}stack;

void push(int num, stack **p2top)
{
 stack *new_node = (stack *)malloc(sizeof(stack));
 new_node -> data = num;
 new_node -> next = *p2top;
 *p2top = new_node;
}

int pop(stack **p2top)
{
 int ret;

 if(*p2top != NULL){
  ret = (*p2top) -> data;
  *p2top = (*p2top) -> next;
 }
 else
  return 0;

 return ret;
}

void show(int hanois, stack *top1, stack *top2, stack *top3)
{
 int i, tmp __attribute__((unused));
 for(i=0; i<hanois; i++){
  printf("%d/t%d/t%d/n", pop(&top1), pop(&top2), pop(&top3));
 }
 printf("-----------------/n");
}

void towers_of_hanoi(int hanois, stack **p2top1, stack **p2top2, stack **p2top3)
{
 int tmp;
 if(hanois > 0){
  towers_of_hanoi(hanois-1, p2top1, p2top3, p2top2);

  tmp = pop(p2top1);
  push(tmp, p2top2);

  towers_of_hanoi(hanois-1, p2top3, p2top2, p2top1);
 }
}

void init(stack **p2top, int hanois)
{
 int i;
 if(hanois > 0){
  for(i=0; i<hanois; i++){
   push(hanois-i, p2top);
  }
 }
 else
  return;
}

int main(void)
{
 printf("how many hanois ? ");
 int hanois;
 scanf("%d", &hanois);

 stack *top1 = NULL, *top2 = NULL, *top3 = NULL;
 init(&top1, hanois);

 show(hanois, top1, top2, top3);
 towers_of_hanoi(hanois, &top1, &top2, &top3);
 show(hanois, top1, top2, top3);

 return 0;
}

原创粉丝点击