首页 > 解决方案 > 我应该怎么做才能使链表中的最后一个节点参与冒泡排序?

问题描述

我写了一个链表程序,我应该编写一个冒泡排序功能,但是最后一个节点似乎没有参与冒泡排序。我猜那是因为指针移动到 NULL 并拒绝最后一个节点数据。您能否建议我一种以任何其他方式对链接列表进行排序的方法,这也会有所帮助。

我的代码是:

#include<stdio.h>
#include<stdlib.h>
typedef struct node_type{
   int data;
   struct node_type *next;
}node;

typedef node *list;
list head;

void traverse()
{
   list temp;
   temp=head;
   printf("\nThe Data is: \n");
   while(temp!=NULL)
   {
      printf("%d\n",temp->data);
      temp=temp->next;
   }
   printf("\n\n");
}

void sort_list()
{
   list new,ptr;
   int temp;
   for(new=head;new->next!=NULL;new=new->next)
   {
       for(ptr=new->next;ptr->next!=NULL;ptr=ptr->next)
       {
           if(new->data > ptr->data)
              {
                  temp=new->data;
                  new->data=ptr->data;
                  ptr->data=temp;
              }  
        }
   }
   traverse();
   }

void main()
      {
         list temp,new;
         head=NULL;
         int n;
         char ch;
         temp=(list) malloc(sizeof(node));
         printf("\nGive data: ");
         scanf("%d",&temp->data);
         head=temp;
         printf("\n");
         printf("Enter more data(y/n): ");
         scanf("\n%c",&ch);
         while(ch=='y')
            {
               new=(list) malloc(sizeof(node));
               printf("Give data: ");
               scanf("%d",&new->data);
               temp->next=new;
               temp=new;
               printf("\nEnter more data(y/n): ");
               scanf("\n%c",&ch);
            }
       temp->next=NULL;
       traverse(head);
       printf("\n\nDo you want to sort the Link-List(y/n): ");
       scanf("\n%c",&ch);
       if(ch=='y')
          { 
             sort_list();
          }
    }

输入:2 3 1 5 4

输出:1 2 3 5 4

标签: cpointersdata-structureslinked-list

解决方案


由于循环中的条件,内部循环sort_list()在排序期间不考虑最后一个节点。你应该检查它:ptr->next!=NULLforptrNULL

for(ptr = new->next; ptr != NULL; ptr = ptr->next)
                     ^^^^

推荐阅读