프로그래밍[Univ]/데이터구조

[스택] 링크드리스트를 이용한 stack 5/27

Cloud Travel 2011. 5. 27. 12:51

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

typedef struct nodetype{  // 노드의 형식
 int data;
 struct nodetype *next_ptr;
}node;

typedef struct stacktype{  // 리스트 스택의 형식
 int count;
 node *head_ptr;
}stack;

stack *makestack(){  // 스택을 만듭니다.
 stack *returnstack;  // 반환한 스택을 생성후
 returnstack = (stack *)malloc(sizeof(stack)); // 메모리할당을 한후
 if( returnstack != NULL ){ // 검사를 해줍니다.
  memset(returnstack,0,sizeof(stack)); // 초기화를 한후에
  return returnstack; // 반환해줍니다.
 }else{
  printf("Error!! Memory\n");
  return 0;
 }
 return 0;
}

void Push(stack *Pstack, node d){  // 자료를 삽입합니다.
 node *newnode = (node *)malloc(sizeof(node));  // 새로운 노드타입을 만든후
 *newnode = d;  // 메인에서 받은 노드를 받은후
 newnode -> next_ptr = Pstack -> head_ptr; // 링크의 맨앞에 넣어 줍니다.
 Pstack -> head_ptr = newnode;
 Pstack -> count++; // 자료 개수 한단계 상승
}

void Pop(stack *Pstack){ // 자료를 삭제 합니다.
 if ( Pstack -> count > 0 ){
  node *freenode;  // 삭제될 자료를 저장해준후 메모리 반환을 해주는 변수
  freenode = Pstack -> head_ptr; 
  Pstack -> head_ptr = Pstack -> head_ptr -> next_ptr;  // 연결을 끈습니다.
  printf("Pop data : %d\n",freenode -> data);  // Pop값을 알려준 후
  if ( freenode != NULL ){
   free(freenode);  // 메모리 반환을 해주고
  }
  Pstack -> count--;  // 자료 개수를 한단계 낮춥니다.
  return ;
 }else{
  printf("Error!! Empty\n");
  return ;
 }
}

void Peek(stack *Pstack){
 if ( Pstack -> count > 0 ){
  printf("Peek data : %d\n",Pstack -> head_ptr -> data);  // 맨위층의 자료를 추출합니다.
  return ;
 }else{
  printf("Error!! Empty\n");
  return ;
 }
}

void Display(stack *Pstack){
 int i;
 node *temp = Pstack -> head_ptr;
 for ( i = Pstack -> count ; i > 0 ; i-- ){
  printf("%d층 값 : %d\n",i,temp->data);
  temp = temp -> next_ptr;
 }
 return ;
}

int main(){
 stack *Lstack;
 Lstack = makestack();

 printf("You make stack\n");
 while(1){
  int select;
  node datanode;

  printf("\n\n\n%d층의 스택이 형성되어있음!!\n",Lstack -> count);
  printf("You Select Number!!\n");
  printf("1.Push\t2.Pop\t3.Peek\t4.Display\t5.End\n");
  printf("Number : ");
  scanf("%d",&select);
  switch(select){
   case 1:
    printf("Input Data : ");
    scanf("%d",&datanode.data);
    Push(Lstack,datanode);
    break;
   case 2:
    Pop(Lstack);
    break;
   case 3:
    Peek(Lstack);
    break;
   case 4:
    Display(Lstack);
    break;
   case 5:
    if ( Lstack != NULL ){
     free(Lstack);
    }
    return;
   default :
    printf("You select wrong number!\n");
  }
 }
}

----------------------------------------------------------------------------------------------------


링크드 리스트로 구연한 stack에서는 자료의 최상위를 자료의 맨앞에 두는 특징이있다.

이는 자료의 추가 삭제가 맨 앞에서 이뤄지는 것이 용이 하기 때문에 이다.