본문 바로가기

데이터구조/소스코드

OJ 1160

반응형
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
	int data;
	struct node *prev;
	struct node *next;
};
struct node *head = 0;

void goHome(int who, int step)
{
	struct node *temp = head;
	while (temp->data != who)
	{
		temp = temp->next;
	}

	while (1)
	{
		for (int i = 0; i < step; i++)
		{
			temp = temp->next;
		}
		struct node *cur = temp->prev;
		cur->prev->next = temp;
		temp->prev = cur->prev;
		printf("%d ", cur->data);
		free(cur);

		if (temp->next == temp)
		{
			printf("%d ", temp->data);
			free(temp);
			break;
		}
	}
}

void connectToRing()
{
	struct node *temp = head;
	while (temp->next != 0)
	{
		temp = temp->next;
	}
	head->prev = temp;
	temp->next = head;
}

void addToDLL(int _data)
{
	struct node *cur;
	cur = (struct node *)malloc(sizeof(struct node));
	cur->next = cur->prev = 0;
	cur->data = _data;

	if (head == 0)
	{
		head = cur;
		return;
	}
	else
	{
		// add cur to the end of DLL
		struct node *temp = head;
		while (temp->next != 0)
		{
			temp = temp->next;
		}
		temp->next = cur;
		cur->prev = temp;
	}
}

int main(void)
{
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		addToDLL(i);
	}
	connectToRing();
	int who;
	int step;
	scanf("%d %d", &who, &step);

	goHome(who, step);
	return 0;
}
반응형

'데이터구조 > 소스코드' 카테고리의 다른 글

BST를 이용한 영어/한글 단어관리 프로그램 소스  (0) 2016.05.09
OJ 1161  (0) 2016.04.25
OJ 1165  (0) 2016.04.25
OJ 1165  (0) 2016.04.25
OJ 1164  (0) 2016.04.25