首页 > 解决方案 > 链表中的排序插入程序

问题描述

我是数据结构的初学者,现在正在学习链表。我遇到了一个关于排序插入的程序,其中我有一个 add() 函数来按排序顺序添加节点

         /*Linked List program to add ascending order sorted nodes in     

         the list */
 #include <stdio.h>
  #include <stdlib.h>
enter code here
 struct node {
   int data ;
   struct node link;

 };

 void add(struct node **q,int num){
    struct node *r,*temp = *q;
    r = malloc(sizeof(struct node )); //Data Allocated
    r->data = num;

    if(*q==NULL ||(*q)->data >num){
     *q = r;
     (*q)->link = temp;

    }else{
      while(temp !=NULL){
         if(temp->data <=num &&(temp->link->data >num                    
                                             ||temp->link==NULL)){
             r->link = temp->link;
             temp->link=r;
             return;
         }
          temp = temp->link;
      }

    }

 }

 void main(){
 struct node *p;
 p = NULL;

 }

我希望按升序添加节点,但是当我输入数据时会显示错误。我正在使用代码块在 C 中运行程序

我认为它必须与结束条件 temp->link == null 相关,但我无法确定该部分代码的确切条件。请帮助!

标签: clinked-listsingly-linked-list

解决方案


  1. 结构的定义struct node不正确。我认为这是一个错字。它应该是struct node *link;

  2. 您遍历循环的条件不正确。如评论中所述,您正在访问temp->link以防万一NULL

  3. 您没有检查要添加的数字大于所有数字并且要添加到列表末尾的条件。

修改后的功能如下。

 void add(struct node **q,int num){
    struct node *r,*temp = *q;
    r = malloc(sizeof(struct node )); //Data Allocated
    r->data = num;
    r->link = NULL;

    if(*q==NULL ||(*q)->data >num){
     *q = r;
     (*q)->link = temp;

    }else{
      while(temp->link !=NULL){
         if(temp->data <=num &&(temp->link->data >num)){
             r->link = temp->link;
             temp->link=r;
             return;
         }
         temp = temp->link;
      }
      temp ->link = r; // add at the end as not added at any other location.
    }
}

推荐阅读