VioletaBabel

1874번:스택 수열 본문

백준/백준-C
1874번:스택 수열
Beabletoet 2017. 4. 19. 22:05


#include <stdio.h>

#include <stdlib.h>//malloc

#include <string.h>

#define mal (node *)malloc(sizeof(node))

typedef struct _node

{

int data;

struct _node *next;

}node;


node *head, *end, *indexnode;

void push(int num);

void pop();


void push(int num)

{

indexnode = (node *)malloc(sizeof(node));

indexnode->data = num;

indexnode->next = head->next;

head->next = indexnode;

printf("+\n");

}


void pop()

{

indexnode = head->next;

head->next = indexnode->next;

free(indexnode);

printf("-\n");

}


int main()

{

head = mal;

end = mal;

int N, a, top=0, no = 0;

head->next = end;

end->next = end;

scanf("%d", &N);

for (int i = 0; i < N; ++i)

{

scanf("%d", &a);

while (1)

if (head->next->data < a)

push(++top);

else if (head->next->data == a)

{

pop();

break;

}

else

{

printf("NO");

no = 1;

break;

}

if (no == 1)

break;

}

}


----------위 코드로 하니 계속 출력초과.

원인이 뭘까 찾아봤더니

이번엔 그때그때 결과를 출력하는게 아니라, 숫자를 다 입력받은 후 한번에 출력해야 하는 모양인가보다.


그래서 아래와 같이 수정.


#include <stdio.h>

#include <stdlib.h>//malloc

#include <string.h>

#define mal (node *)malloc(sizeof(node))

typedef struct _node

{

int data;

struct _node *next;

}node;


node *head, *end, *indexnode;

char pm[200001];

void push(int num, int i);

void pop(int i);


void push(int num, int i)

{

indexnode = (node *)malloc(sizeof(node));

indexnode->data = num;

indexnode->next = head->next;

head->next = indexnode;

pm[i] = '+';

}


void pop(int i)

{

indexnode = head->next;

head->next = indexnode->next;

free(indexnode);

pm[i] = '-';

}


int main()

{

head = mal;

end = mal;

int N, a[100001], top = 0, no = 0;

memset(a, 0, sizeof(a));

head->next = end;

end->next = end;

scanf("%d", &N);

for (int i = 0; i < N; ++i)

scanf("%d", &a[i]);

for (int i = 0, j = -1; i < N; ++i)

{

while (1)

{

++j;

if (head->next->data < a[i])

push(++top, j);

else if (head->next->data == a[i])

{

pop(j);

break;

}

else

{

printf("NO\n");

no = 1;

break;

}

}

if (no == 1)

break;

}

if (no != 1)

for (int i = 0; pm[i] != '\0'; ++i)

printf("%c\n", pm[i]);

}

'백준 > 백준-C' 카테고리의 다른 글

2750번: 수 정렬하기  (0) 2017.05.02
11866번: 조세퍼스 문제  (0) 2017.04.25
10845번: 큐  (0) 2017.04.21
9012번: 괄호  (0) 2017.04.20
10828번: 스택  (0) 2017.04.19
Comments