使用双向链表进行排序的问题

时间:2014-11-25 17:08:37

标签: c sorting debugging segmentation-fault

我试图通过C中的以下方法实现排序 - 接受整数并将它们保存到数组中。传递每个数组值并按升序排列在双向链表中。我已经编写了程序但是我遇到了崩溃,调试显示它在显示功能中存在分段错误,但是我仍然无法做到这一点。 提示将不胜感激。

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

struct node //Doubly linked list to store in ascending order
{
    int info;
    struct node *llink; //Left link
    struct node *rlink; //Right link
};

typedef struct node *NODE; //Define a custom data type for pointer to node(a structure)

/*Accept an integer argument and insert into a doubly linked list at appropriate position to arrange in ascending order*/
void list_sort(NODE head,int item)
{
    NODE cur,prev,temp,prev_to_prev;
    temp=malloc(sizeof(struct node)); //Allocate block of memory for a new node to be inserted
    temp->info=item; //Assign the integer to info field of the node
    if(head->rlink==NULL) //head->rlink==NULL when the first node is being inserted
    {
        head->rlink=temp;
        temp->llink=head;
        temp->rlink=head; //Last points to first because of circular representation used here
        return;
    }
        cur=head->rlink;
        while(cur!=head)
        {
            prev=cur->llink;
            if(temp->info<cur->info&&temp->info>=prev->info) //when  prev->info<temp->info<cur->info insert between prev and cur
            {
                prev->rlink=temp;
                temp->llink=prev;
                cur->llink=temp;
                temp->rlink=cur;
                return;
            }
            else if(temp->info>=cur->info && temp->info>prev->info) // when temp->info>cur->info and also > prev->info insert at last
            {
                cur->rlink=temp;
                temp->llink=cur;
                return;
            }
            else if(temp->info<cur->info && temp->info<prev->info) // when temp->info<cur->info and also < prev->info insert before them
            {
                prev_to_prev = prev->llink;
                prev_to_prev->rlink=temp;
                temp->rlink=prev;
                return;
            }
        cur=cur->rlink;
        }
}

void list_disp(NODE head)
{
    NODE cur;
    printf("\nSorted elements are - \n");
    cur=head->rlink;
    while(cur!=head)
    {
        printf("%d\n",cur->info);
        cur=cur->rlink;
    }

}

void main()
{
    int items[10],i;
    NODE head,cur;
    head=malloc(sizeof(struct node));
    head->llink=head->rlink=NULL;
    head->info=0;
    printf("Enter 5 items to sort: \n"); //Take only 5 items for now
    for(i=0;i<5;i++)
        scanf("%d",&items[i]); //Read 5 items
    for(i=0;i<5;i++)
        list_sort(head,items[i]); //Call function for all 5 items
    list_disp(head); //Display the linked list entry by entry 

}

1 个答案:

答案 0 :(得分:1)

一个潜在的问题是,在某些情况下,您没有初始化rlinkllink

另一个是你使用简单赋值运算符而不是等价的事实:

temp->info>=cur->info