2013-07-10 2 views
0

나는 연결된 목록을 사용하고 where 노드 아래에 데이터 d가있는 새 노드를 삽입하려고 시도하고 있습니다. 어떤 이유로 나는 잘못된 결과를 얻고 있습니다. 여기 내 코드입니다 :n 번째 요소 뒤에 연결된 목록에 삽입

void insertAfter(int d, int where) 
{ 
    struct list * marker = head; 
    struct list * new; 

    while(marker -> data != where) 
     marker = marker -> next; 
    new = (struct list*)malloc(sizeof(struct list)); 

    new -> next = marker -> next; 
    marker -> next = new; 
    new -> data = d; 
} 
+0

'marker -> data! = where'는 n 번째를 의미하지 않습니다. – BLUEPIXY

답변

0

어쩌면이 같은 코드를 수정 할 수있는 (첫 번째 노드가 0 번째 노드, 두 번째 노드는 내 코드에 번째입니다) :

void insertAfter(int d, int where) 
{ 
    struct list * marker = head; 
    struct list * new; 
    int count = 0; 

    while(count < where) 
    { 
     count++; 
     marker = marker -> next; 
    } 
    new = (struct list*)malloc(sizeof(struct list)); 

    new -> next = marker -> next; 
    marker -> next = new; 
    new -> data = d; 
} 
1

내가 제안 할 수 있습니다 약간의 해설과 함께 안전한 버전 :

void insertAfter(int d, int where) 
{ 
    struct list * marker = head; /* it's a little odd that you have named your node struct list */ 
    struct list * new; 

    while(marker && marker->data != where) /* we don't want to end up dereferencing a null pointer */ 
     marker = marker->next; 

    if (!marker) /* we've reached the end of the list and no element was found */ 
    { 
     printf("Element with data %d not found\n", where); /* print some diagnostics */ 
     return; /* let's exit here, no reason to hang about */ 
    } 

    /* if we are here then we've found our element */ 

    struct list * next_node = marker->next; /* let's save the next node */ 

    new = malloc(sizeof(struct list)); /* it is bad practice to cast the result of malloc */ 
    new->data = d; 

    marker->next = new; /* marker now points to the new node */ 

    new->next = next_node; /* the new node now points to the one marker originally pointed to */ 
} 

malloc의 캐스팅에 관해서는 here에 대한 읽기 있습니다.

0

코드는 어디에 노드가 아닌 데이터 == 노드 뒤에 새 노드를 삽입합니다. 이처럼 쓸 수 있습니다 :

int i; 
for(i=1; i<where; i++) 
    marker = marker->next; 

게다가, markerNULL 도달하거나 프로그램이 marker->next 또는 marker->data을 읽으려고 할 때, 중단이있을 것입니다 있는지 확인하는 것이 좋습니다.