Data Structure/윤성우의 열혈 자료구조

문제 04-1 연결 리스트 관련 코드에 익숙해지기

100win10 2019. 9. 5. 20:55

예제에서는 노드를 머리가 아닌 꼬리에 추가하였다. 따라서 3 - 2 - 7 - 8 순으로 연결되어 있는 리스트에 5를 추가로 삽입하면 3 - 2 - 7 - 8 - 5의 순으로


저장이 된다. 그런데 이번에는 다음 순으로 저장이 되도록 예제를 변경해 보고자 한다. 5 - 8 - 7 - 2 - 3


즉 연결리스트의 머리에 노드가 추가되도록 하자.


코드 


#include <stdio.h>

#include <stdlib.h>

#pragma warning(disable:4996)

typedef struct _node

{

int data;

struct _node *next;

} Node;

int main(void)

{

Node * head = NULL;

Node * tail = NULL;

Node * cur = NULL;

while (1)

{

int temp;

printf("자연수 입력: ");

scanf("%d", &temp);

if (temp < 1)

break;

Node * newnode = (Node*)malloc(sizeof(Node));

newnode->data = temp;

newnode->next = NULL;


if (head == NULL) {

head = newnode;

tail = newnode;

}

else

{

newnode->next = head;

head = newnode;

}

}

printf("\n");

if (head == NULL) {

printf("없습니다.");

}

else

{

cur = head;

printf("%d ", cur->data);


while (cur->next != NULL) {

cur = cur->next;

printf("%d ", cur->data);

}

}

printf("\n");


if (head == NULL)

return 0;

else

{

Node * delnode = head;

Node * delnextNode = head->next;


printf("%d 를 삭제합니다.", delnode->data);

printf("\n");

free(delnode);

while (delnextNode != NULL)

{

delnode = delnextNode;

delnextNode = delnextNode->next;

printf("%d 를 삭제합니다.", delnode->data);

printf("\n");

free(delnode);

}

}

return 0;

}