본문 바로가기

데이터구조/소스코드

OJ 1131번 해답

반응형
SMALL
  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
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <stdio.h>
#include <stdlib.h>

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

// returns the pointer to the node which has _data
// returns null if no node has _data
struct node* whereIsNode(int _data)
{
	struct node *temp = head;

	while (temp != 0)
	{
		if (temp->data == _data)
		{
			break;
		}
		temp = temp->next;
	}
	return temp;

}





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

	// check if there is no node
	if (head == 0)
	{
		head = cur;
		return;
	}

	// find the last node
	{
		struct node *temp = head;
		while (temp->next != 0)
		{
			temp = temp->next;
		}
		temp->next = cur;
		cur->prev = temp;
		return;
	}
}

void showDLL()
{
	struct node *cur = head;
	while (cur != 0)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
}

void showNeighbors(int _data)
{
	struct node *temp;
	temp = whereIsNode(_data);

	if (temp == 0)
	{
		printf("-999\n");
		return;
	}
	else
	{
		// prev prev
		if (temp->prev != 0)
		{
			if (temp->prev->prev != 0)
			{
				printf("%d ", temp->prev->prev->data);
			}
			else
			{
				printf("-999 ");
			}
		}
		else
		{
			printf("-999 ");
		}

		// next next
		if (temp->next != 0)
		{
			if (temp->next->next != 0)
			{
				printf("%d \n", temp->next->next->data);
			}
			else
			{
				printf("-999 \n");
			}
		}
		else
		{
			printf("-999 \n");
		}

	}


}

int main(void)
{
	addToDLL(1);
	addToDLL(2);
	addToDLL(3);
	addToDLL(4);
	addToDLL(5);
	addToDLL(6);
	addToDLL(7);
	addToDLL(8);

	showNeighbors(5); // 3, 7
	showNeighbors(8); // 6, -999
	showNeighbors(1); // -999, 3
	showNeighbors(100); // -999

	return 0;
}
반응형
LIST

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

SLL with character string member  (0) 2016.04.14
String function review  (0) 2016.04.14
OJ 1132번 해답  (0) 2016.04.11
Online Judge 1117 문제의 해답  (0) 2016.04.04
Queue 구현코드 (큐)  (0) 2016.04.04