2014-07-14 2 views
-1

다음은 직접 만들려고 시도한 프로그램입니다. 중간에 노드를 입력하여 정렬 된 링크 목록을 출력으로 제공하고 싶습니다. 하지만 작동하지 않습니다. 그래서 친절하게도 완벽한 결과물을 얻을 수있게 도와 줘요. 그리고이 코드에서 잘못된 점을 이해하게 하죠?정렬 된 링크 된 목록을 만들기 위해 중간에 노드를 입력하십시오

#include<stdio.h> 
#include<stdlib.h> 
typedef struct node_type 
{ 
    int roll_no; 
    char name[10]; 
    float marks; 
    struct node_type *next; 
} node; 
typedef node *list; 
void show_list (list); 
main() 
{ 
    list head, temp, tail; 
    char ch; 
    int n; 
    head = NULL; 
    printf ("Do you want to add?(y/n)"); 
    scanf ("%c", &ch); 
    if (ch == 'y' || ch == 'Y') 
    { 
     tail = (list) malloc (sizeof (node)); 
     printf ("Enter the value for roll number:-\n"); 
     scanf ("%d", &(tail->roll_no)); 
     printf ("Enter name:-\n"); 
     scanf ("%s", tail->name); 
     printf ("Enter marks:-\n"); 
     scanf ("%f", &(tail->marks)); 
     tail->next = head; 
     head = tail; 
     printf ("Enter more data?(y/n)\n"); 
     scanf ("\n%c", &ch); 
    } 
    while (ch == 'y' || ch == 'Y') 
    { 
     tail->next = (list) malloc (sizeof (node)); 
     printf ("Enter the value for roll number:-\n"); 
     scanf ("%d", &(tail->next->roll_no)); 
     printf ("Enter name:-\n"); 
     scanf ("%s", tail->next->name); 
     printf ("Enter marks:-\n"); 
     scanf ("%f", &(tail->next->marks)); 
     temp = tail; 
     printf ("Enter more data?(y/n)\n"); 
     scanf ("\n%c", &ch); 
    } 
    while (temp->roll_no < tail->roll_no) 
    { 
     head = tail; 
     tail = tail->next; 
     temp->next = tail; 
     head->next = temp; 
    } 
    show_list (head); 
} 

void 
show_list (list start) 
{ 
    while (start != NULL) 
    { 
     printf ("%d \t %s \t %f \n", start->roll_no, start->name, 
     start->marks); 
     start = start->next; 
    } 
} 
+0

문제점은 무엇입니까? – Krumia

+0

정렬 방식으로 링크 목록을 가져 오지 않습니다. – Muskaan

답변

0

while (ch == 'y' || ch == 'Y') 문은 목록 끝에 데이터를 계속 추가합니다.

이전의 while 루프를 종료하면 temp = tail을 종료하기 때문에 문 조건은 평가되지 않습니다. 알고리즘에 대해 생각하고 다시 시도하십시오.

힌트 :

  1. 세그먼트 코드
  2. 는 노드 node *createNode()를 만들고에 대한 포인터를 반환하는 기능을합니다.
  3. while(1) { 
         /* < 
          code that checks if you want to continue 
          and breaks out of the loop otherwise 
         >*/ 
    
        insertNode(head, createNode()) 
    } 
    

    등의 기능을 분리 할 수 ​​있습니다, 그리고 다른 기능 void insertNode(node * start, node *newNode)

를 확인하면 모든 작업이 완료된다.

당신은 이미 createNode()을 거의 완성했습니다. 다른 하나는 좀 더 작업하십시오.

0

삽입 메커니즘이 잘못되었습니다. 항상 두 번째 위치에 추가/덮어 쓰기됩니다. 첫 번째 while 루프의 끝에 다음 두 문을 추가하여이를 수정하십시오.

tail = tail-> next;

tail-> next = NULL;

그런 다음 두 번째 while 루프는 완전히 의미가 없습니다.

그런 다음 목록을 트래버스하고 정렬하십시오.


그렇지 않으면 노드를 추가하는 동안 목록을 정렬 할 수 있습니다. 이 경우 프로그램에서 두 개의 while 루프를 다음 코드로 바꿉니다.