1

포인터 및 주소 개념을 향상시키기 위해 연결된 목록을 만들려고합니다. 다음과 같은 방법으로 연결된 목록을 만들어야합니다.링크 된 목록은 인쇄시 첫 번째 노드 요소 만 표시합니다.

(1) 모든 노드를 터미널에서 동시에 읽습니다.

(2) 그런 다음 마지막으로 형성된 최종 연결 목록을 표시하십시오.

어떻게 그렇게하려고합니까? 먼저 연결된 목록의 크기 (입력 할 총 노드 수)를 읽습니다. 그럼 내가 루프를 do-while 루프에서 하나씩 모든 노드를 읽어보십시오. 모든 노드를 읽은 후 연결된 목록을 만들려고합니다. 노드가 첫 번째 노드 일 때 count 변수에 의해 대소 문자가 구별됩니다.이 노드는 다른 루프에있을 때 노드가 첫 번째 노드 일 때 count=0이됩니다.

는 다음과 내가 얻을 출력은 같이

enter the size of node 
4 
start entering the number of elements until your size 
2 
3 
4 
5 
Printing linked list 
2-> //It don't print the other nodes, Just first one 
[email protected]:~/Desktop/pointer$ 

그렇게 할 내 전체 코드는 다음과 같습니다

#include <stdio.h> 
#include <stdlib.h> 
#include <malloc.h> 
#include <string.h> 

struct node 
{ 
    int freq; 
    struct node * next; 
}; 
typedef struct node node; 
node * tree; 

void main() 
{ 
    int size, data; 
    int count = 0; //this count flag is to check is it's first node or not inside the do-while loop. 
    tree = NULL; 
    printf("enter the size of node\n"); 
    scanf("%d", & size); 
    printf("start entering the number of elements until your size\n"); 
    node * temp3 = tree; 
    node * prev; 
    //Problem creating area is below 
    do 
    { 
     scanf("%d", & data); 
     if (count == 0) 
     { 
      node * temp; 
      temp = (node *) malloc(sizeof(node)); 
      temp-> freq = data; 
      temp-> next = NULL; 
      prev = temp; 
     } 
     else if (count != 0) 
     { 
      node * temp; 
      temp = (node *) malloc(sizeof(node)); 
      temp-> freq = data; 
      temp-> next = NULL; 
      prev-> next = temp; 
     } 
     size--; 
     ++count; 
    } 
    while (size > 0); 

    printf("Printing linked list\n"); 
    node * temp1; 
    temp1 = prev; 
    //there may be problem here 
    while (temp1-> next != NULL) 
    { 
     printf("%d-> ", temp1-> freq); 
     temp1 = temp1-> next; 
    } 
    printf("\n"); 
} 

Couldanyone 나에게 에러를 지정하여 전체 연결 목록을 인쇄에서 저를 도와주세요 그게 해결책이야?

+0

여기에 몇 개의 주석이 있습니다 : main은 무언가를 리턴하거나 무효로 설정해야합니다 (트리, temp3 및 저장소), 그리고 내 경우에는 prev 노드를 temp로 설정하고 temp를위한 메모리를 할당하고 기본적으로 가리키는 대상을 덮어 쓴다. –

+0

디버거, debgugger, 디버거 ... –

+0

@JamesHostick 내 편집에 void main()을 유지했습니다. 하지만 문제는 내가 모든 노드를 함께 읽고 있기 때문에 노드를 덮어 쓰는 것을 피하는 방법이다. – user252990

답변

2

내가했습니다 응답의 편의를 위해 만들어지고 있어야한다 코드를 다시 작성하면 내가 한 일을 설명하려고합니다 :

#include <stdio.h> 
#include <stdlib.h> 
#include <malloc.h> 
#include <string.h> 

struct node 
{ 
    int freq; 
    struct node * next; 
}; 
typedef struct node node; 
//only need two pointers when building a linked list, one for the top and one for the 
//current node 
node *tree = NULL, *curr = NULL; //init both pointers to NULL initially 

int main() 
{ 
    int size, data; //dont need count, you'll see in a minute why 
    printf("enter the size of node\n"); 
    scanf("%d", & size); 
    printf("start entering the number of elements until your size\n"); 

    //Problem creating area is below 
    do 
    { 
     scanf("%d", &data); 
     if (tree == NULL) //just test for top node being NULL instead of using count 
     { 
      node *temp; 
      temp = malloc(sizeof(node)); 
      temp->freq = data; 
      temp->next = NULL; 
      //stylistically i like using curr rather than prev, just a style choice 
      tree = temp; //set tree to first node 
      curr = tree; //make the top node the current node 
     } 
     else //don't need else if, there are only two conditions 
     { 
      node *temp = malloc(sizeof(node)); 
      temp->freq = data; 
      temp->next = NULL; 
      curr->next = temp; //set the next node in list to the new one 
      curr = curr->next; //here's where you had pointer issues, move the current 
           //to the newly created node 
     } 
     size--; 
    } 
    while (size > 0); 

    printf("Printing linked list\n"); 
    curr = tree; //reuse curr, no need to make a new pointer 

    //test for the current node being NULL, takes care of special case of empty list 
    //causing a segfault when you attempt to access a member of an invalid pointer 
    while (curr != NULL) 
    { 
     printf("%d->", curr->freq); 
     curr = curr->next; //move to next item in list 
    } 
    printf("\n"); 
    return 0; 
} 

3의 크기와 1, 2, 3의 입력으로 실행되는 샘플을 출력으로 얻습니다. 1-> 2-> 3->

+1

mallocs를 사용하여 오류를 테스트하지는 않았지만 malloc 후에 포인터가 메모리를 할당했는지 즉시 테스트하는 것이 좋습니다. 그렇지 않으면 어떤 종류의 오류 메시지가 인쇄됩니다. –

+0

감사합니다. 내 많은 의문점을 제거했습니다. 도움을 주셔서 감사합니다 – user252990

+1

아무 문제 없어요, 포인터를 사랑하고, 포인터가 싫어. 그리고 포인터를 싫어하는 걸 좋아해. –

2

두 가지 문제가 있습니다.

else if (count != 0) 
    { 
     node * temp = prev; 
     temp = (node *) malloc(sizeof(node)); 
     temp-> freq = data; 
     temp-> next = NULL; 
     prev-> next = temp; 
    } 

이전 노드에서 새 노드를 가리 키지 않습니다. 시나리오에서 여전히 '2'를 가리키며 목록에 두 개 이상의 노드가 없을 것입니다.

else if (count != 0) 
    { 
     /* node * temp = prev; */ //This code is not doing anything useful 
     temp = (node *) malloc(sizeof(node)); 
     temp-> freq = data; 
     temp-> next = NULL; 
     prev-> next = temp; 
     prev = temp; 
    } 

다음과 같은

시도 뭔가, 프린팅 루프는 아마도 불필요한 포인터와 몇 가지 포인터 실수가 좋아

node* temp1 = start; //You need a variable that points to the first node in the list 
do 
{ 
    printf("%d-> ", temp1-> freq); 
    temp1 = temp1-> next; 
} 
//The last item will always have next == NULL, and must be included 
while (temp1-> next != NULL); 
+0

구조체 포인터의 멤버에 액세스 할 때 세 번째 코드 블록에 대해 여기에서 한 가지 유의해야 할 점은 포인터가 유효한지 확인해야합니다. 액세스. 그렇지 않으면 segfault가 생깁니다. 확률은 유효한 포인터가 시작되는 한은 아니지만 사용자가 무언가를 망치지 않았다는 것을 확신 할 수는 없습니다. :) –

+0

@Archa 고마워요.하지만 둘 다 방금 말했습니다. 아무도 일하지 않았습니다. – user252990

+0

"시작"을 사용하지 않고 "트리"를 사용하고 있습니다. – user252990

관련 문제