Linked List는 각 노드가 데이터와 포인터를 가지고 한 줄로 연결되어 있는 방식으로 데이터를 저장하는 자료 구조이다.
* Simple Linked List
#include <stdio.h>
#include <malloc.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *head, *tail;
void insertNode(int data)
{
Node* node = head;
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
while (node->next != tail) {
node = node->next;
}
newNode->next = node->next;
node->next = newNode;
}
void deleteNode(int key)
{
Node* curNode = head->next;
Node* prevNode = head;
while ((curNode->data != key) && (curNode != tail)) {
prevNode = curNode;
curNode = curNode->next;
}
if (curNode != tail) {
prevNode->next = curNode->next;
free(curNode);
}
}
Node* findNode(int key) {
Node* node;
node = head->next;
while ((node->data != key) && (node != tail)) {
node = node->next;
}
return node;
}
void printList() {
Node* node = head->next;
printf("LinkedList :");
while (node != tail) {
printf(" %d", node->data);
node = node->next;
}
printf("\n");
}
void clear() {
Node* node = head;
Node* delNode;
while (node != NULL) {
delNode = node;
node = node->next;
free(delNode);
}
}
int main()
{
head = (Node*)malloc(sizeof(Node));
tail = (Node*)malloc(sizeof(Node));
head->next = tail;
tail->next = NULL;
insertNode(5);
insertNode(3);
insertNode(1);
insertNode(4);
insertNode(2);
printList();
printf("findNode() - %d\n", findNode(1)->data);
deleteNode(4);
printList();
clear();
return 0;
}
#include <malloc.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *head, *tail;
void insertNode(int data)
{
Node* node = head;
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
while (node->next != tail) {
node = node->next;
}
newNode->next = node->next;
node->next = newNode;
}
void deleteNode(int key)
{
Node* curNode = head->next;
Node* prevNode = head;
while ((curNode->data != key) && (curNode != tail)) {
prevNode = curNode;
curNode = curNode->next;
}
if (curNode != tail) {
prevNode->next = curNode->next;
free(curNode);
}
}
Node* findNode(int key) {
Node* node;
node = head->next;
while ((node->data != key) && (node != tail)) {
node = node->next;
}
return node;
}
void printList() {
Node* node = head->next;
printf("LinkedList :");
while (node != tail) {
printf(" %d", node->data);
node = node->next;
}
printf("\n");
}
void clear() {
Node* node = head;
Node* delNode;
while (node != NULL) {
delNode = node;
node = node->next;
free(delNode);
}
}
int main()
{
head = (Node*)malloc(sizeof(Node));
tail = (Node*)malloc(sizeof(Node));
head->next = tail;
tail->next = NULL;
insertNode(5);
insertNode(3);
insertNode(1);
insertNode(4);
insertNode(2);
printList();
printf("findNode() - %d\n", findNode(1)->data);
deleteNode(4);
printList();
clear();
return 0;
}
* 출처 : https://www.tutorialspoint.com/data_structures_algorithms/
'SW > 자료구조' 카테고리의 다른 글
Circular Queue (0) | 2019.01.06 |
---|---|
Queue (0) | 2019.01.06 |
Stack (0) | 2019.01.06 |
Linked List 3 - Circular Linked List (0) | 2019.01.06 |
Linked List 2 - Doubly Linked List (0) | 2019.01.06 |