티스토리 뷰

// LinkedStack.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//


#include "stdafx.h"

// 단일 포인터 이용

struct Node
{
      int data;
      Node *next;
};

Node *head = 0;

void Push(int r)
{
      Node *p = new Node;
      p->data = r;
      p->next = head;
      head = p;
}

int Pop()
{
      Node *p = head;
      head = p->next;
      int r = p->data;
      delete p;
      return r;
}

int _tmain(int argc, _TCHAR* argv[])
{
      for( int i = 1; i <= 10; i++ )
            Push(i);

      for( int i = 0; i < 10; i++ )
            printf( "%d ", Pop() );
      printf( "\n" );

      return 0;
}

실행결과



#include "stdafx.h"

// 이중 포인터 이용

struct Node
{
      int data;
      Node *next;
};

void Push(Node **head, int r)
{
      Node *p = new Node;
      p->data = r;
      p->next = *head;
      *head = p;
}

int Pop(Node **head)
{
      Node *p = *head;
      *head = p->next;
      int r = p->data;
      delete p;
      return r;
}

int _tmain(int argc, _TCHAR* argv[])
{
      Node *head = 0;

      for( int i = 1; i <= 10; i++ )
            Push(&head, i);

      for( int i = 0; i < 10; i++ )
            printf( "%d ", Pop(&head) );
      printf( "\n" );

      return 0;
}

실행결과