C언어 단순연결리스트 관련 질문입니다.
글쓴이: acacia93 / 작성시간: 일, 2017/04/16 - 9:52오후
(1) insert_node 리스트를 구성하고 출력하라.
(2) remove_node 리스트를 초기화하고 출력하라.
(3) add(ListNode **phead, int pos, element data), ListNode *get_node_at(ListNode *phead, int pos) 리스트를 구성하고 리스트 내용을 프린트하라.
위 내용이 제가 풀고자하는 문제이고
#include <stdio.h> #include <stdlib.h> typedef int element; typedef struct ListNode { element data; struct ListNode *link; } ListNode; typedef struct { ListNode *head; int length; } ListType; ListNode *create_node(int data, ListNode *link) { ListNode *new_node = (ListNode*)malloc(sizeof(ListNode)); if (new_node == NULL) { puts("메모리 할당 에러"); exit(1); } new_node->data = data; new_node->link = NULL; return new_node; } void insert_node(ListNode **phead, ListNode *p, ListNode *new_node) { if (*phead == NULL) { new_node->link = NULL; *phead = new_node; } else if (p == NULL) { new_node->link = *phead; *phead = new_node; } else { new_node->link = p->link; p->link = new_node; } } ListNode *get_node_at(ListType *list, int pos) { int i; ListNode *tmp_node = list->head; if (pos < 0) return NULL; for (i = 0; i < pos; i++) tmp_node = tmp_node->link; return tmp_node; } void add(ListType *list, int pos, element data) { ListNode *p; if ((pos >= 0) && (pos <= list->length)) { ListNode *node = (ListNode *)malloc(sizeof(ListNode)); if (node == NULL) printf("메모리 할당에러"); node->data = data; p = get_node_at(list, pos - 1); insert_node(&(list->head), p, node); list->length++; } } int remove_node(ListNode **phead, ListNode *p, ListNode *removed) { if (p == NULL) *phead = (*phead)->link; else p->link = removed->link; free(removed); return 0; } void display(ListNode *head) { ListNode *p = head; while (p != NULL) { printf("%d->", p->data); p = p->link; } printf("\n"); } int main(void) { ListType *list2 = NULL; int i; for (i = 10; i > 0; i--) insert_node(&list2->head, NULL, create_node(i, NULL)); display(list2->head); for (i = 0; i < 10; i++) remove_node(&list2->head, NULL, list2->head); display(list2->head); add(list2, NULL, 1); display(list2->head); }
저는 메인만 작성했지만 이게 소스인데,
예외가 throw됨: 쓰기 액세스 위반입니다.
list2이(가) nullptr였습니다.
라는 오류가 뜨면서 실행이 안됩니다.
고칠 곳좀 찾아주실 수 있을까요?ㅠㅠ
계속 낑낑대다가 질문드립니다.
Forums:
베끼더라도 코드는 이해하고 넘어가세요.ListType
베끼더라도 코드는 이해하고 넘어가세요.
댓글 달기