안녕하세요.. C언어 연결리스트 질문드립니다.

코딩왕초보의 이미지

linked list로 전화번호부 작성하기 프로그램인데, add함수를 아무리 머리를 짜내도 방법이 감이 안와서 가입 후 질문 드립니다.
예시를 들면 aaa bbb ccc가 있는 프로그램에 bbc를 add하면 aaa bbb bbc ccc로 정렬되어 추가되는 프로그램인데요, 연결리스트에 대한 개념이 부족해서 그런지, 아무리 수정해봐도 계속 에러가 나는데 이유조차 모르겠습니다...
new_node와 free_node는 아마 맞을거라 생각합니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>    
 
struct record {
  char name[3];
  char number[4];
  struct record * next;
}; // 이름 3개, 숫자 4개를 받아 작성하는 전화번호부
 
void print_name(struct record *);
void print_number(struct record *);
void print_data(char *, int);
 
#define POOL_SIZE 7
 
struct record pool[POOL_SIZE]; 
struct record * top = pool;// pool은 스택의 탑.
 
 
int compare(char key[3], struct record *); // 비교를 위해
 
struct record * data = NULL; 
 
void init_pool() // Initialize the pool
{
  int i;
  struct record *r=pool;
  struct record *s;
 
  pool[POOL_SIZE-1].next=NULL;  
 
  for(i=1;i<POOL_SIZE;i++) { 
    s=r++;
    s->next=r;
  }
}
 
 
// Get a node from the pool.  Returns NULL if pool is empty.
struct record * new_node()  
{
	struct record *p;
	if (top == NULL)
		return NULL;
	p = top;
	top = p->next;
	return p;
 
}
 
// Push 
void free_node(struct record *r)
{
  r->next=top;
  top=r;
}
 
// 이 부분이 문제입니다 !! 모르겠습니다 ㅠㅠ 제가 짜면서도 무슨 코드인지 모르겠어요..
// 밑의 코드는 틀린 코드이니 무시해주셔도 됩니다.
 
void add(char *name, char *number)
{
	struct record *q = new_node();
	struct record *p = top;
	struct record *com = data;
	int result;
 
	q->name[0] = name[0];
	q->name[1] = name[1];
	q->name[2] = name[2];
	q->number[0] = number[0];
	q->number[1] = number[1];
	q->number[2] = number[2];
	q->number[3] = number[3];
 
	while (com != NULL && (result = compare(name, com)) > 0)
		com = com->next;
	if (p == NULL)
	{
		p = q;
		q->next = NULL;
	}
	else
	{
		q->next = com->next;
		com->next = q;
	}
}
 
 
 
}
 
 
 
void search(char name[3])  
{
  struct record *r=data;
  int result;
 
  while(r!=NULL && (result=compare(name,r))>0)
    r=r->next;
  if(r==NULL || result<0)
    printf("Couldn't find the name.\n");
  else {
    print_name(r);
    printf(" : ");
    print_number(r);
    printf(" was found.\n");
  }
}
 
 
void delete(char name[3])
{
	// add함수 작성 이후 테스트하면서 작성하기
}
 
int compare(char key[3], struct record *r)
{
  if (r==NULL)  
    return -1;
  else
    return strncmp(key, r->name, 3);
}

갓 가입해서 도움을 요청하는게 양심 없다는걸 알지만.. 물어볼 곳이 주변에 없어 질문 드립니다.
부탁드립니다 (_ _)

익명 사용자의 이미지

Quote:
제가 짜면서도 무슨 코드인지 모르겠어요

이 부분에 문제가 있네요. 그러면 안 됩니다.

non-trivial한 프로그램은 내가 뭘 하는지 잘 모르는 상황에서 이것저것 수정한다고 완성될 수 있는 게 아니기 때문이지요.

너무 어려운 과제에 도전하고 계신 것 같습니다. 좀 더 기초적인 내용으로 돌아가서 공부하시는 게 좋겠네요.

zooloo의 이미지

직접 구현 안해도 되니, 인터넷 찾아서 다른 링크드리스트 소스 찾아서 배끼세요
구현능력 없다면 다른소스 통으로 외워버리세요
그러면 구현능력이 생기는 겁니다

bushi의 이미지

설계를 하시다 헷갈리신 것 같네요.
현재 코드는 엉망진창이고, 의도하신 대로 하려면 리스트를 두 개 운용하셔야 합니다.
하나는 pool, 다른 하나는 전화번호부.

pool 을 단순 배열로만 운용하시거나,
아예 pool 없이 그때 그때마다 malloc() 하는 것으로 마음을 고쳐 먹으면 머리가 좀 개운해지실 겁니다.

덧:
리스트 공부하기엔 sys/queue.h 도 나쁘지 않습니다.
언젠가 누가 학교 과제를 대신 해달라고 여기다 글을 쓴 걸 보고 F 맞으라며 냅다 내갈긴 코드가
https://kldp.org/files/qqq.c.txt

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.