C中单链接列表的插入排序

问题描述

我正在努力提高对算法和数据结构的了解,因此在过去的5-6天里,我一直在尝试对不同的数据结构实现不同的算法。我具有单,双和循环链表的基本知识,并且可以使用数组实现插入排序算法。

但是,用单链表实现插入排序算法比我最初期望的要麻烦得多。我不喜欢查看别人的代码并复制他们的代码来理解一个概念。我真的很想尝试自己先做。所以,我写了几行:

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

typedef struct Node node;
struct Node{
    int num;
    node *next;
};

void printLinkedList(node *ptr);
void insertionSortLinkedList(node *p,node *head,int sizeOfList);

/* Driver program applying Insertion Sort to a Singly Linked List */
int main(int argc,char *argv[]){
    
    int i,sizeOfList=argc-1;
    node *head,*ptr;
    ptr=(node*)malloc(sizeOfList*sizeof(node));
    for(i=0;i<sizeOfList;i++){
        (ptr+i)->num=atoi(argv[i+1]);
        (ptr+i)->next=(ptr+i+1);
    }
    (ptr + sizeOfList-1)->next=NULL;
    head=ptr;

    printLinkedList(head);

    insertionSortLinkedList(ptr,head,sizeOfList);
    return 0;
}


void printLinkedList(node *ptr) {
    
    while (ptr != NULL) {
        printf("%d ",ptr->num);
        ptr=ptr->next;
    }

    printf("\n\n");
}

void insertionSortLinkedList(node *p,int sizeOfList){
    int i=0;
    int N=1;
    int flag;
    node *temp;
    while(N<sizeOfList){
        flag=0;
        /* node N > node i */
        if((p+N)->num>(p+i)->num){
            i++;
        }
        /* node i >= node N */
        else{
            /* node i = node N */
            if((p+N)->num==(p+i)->num){ // FirsT ERROR HERE. DOES NOT ENTER HERE FOR 2 1 3 1 5 4 3 WHEN 1(i) 2 3 1(N) 5 4 3
                /* i = N */
                if(i==N){
                    flag=1;
                }
                /* i != N */
                else{
                    temp=(p+N);
                    (p+N-1)->next=(p+N)->next;
                    temp->next=(p+i)->next;
                    (p+i)->next=temp;
                    flag=1;
                }
            }
            /* node i > node N */
            else{
                /* i = 0 and Head needs to change */
                if(i==0){ 
                    temp=(p+N);
                    (p+N-1)->next=(p+N)->next;
                    temp->next=(p+i);
                    head=temp;
                    flag=1;
                }
                /* i != 0 and Head needs to change */
                else{
                    temp=(p+N);
                    (p+N-1)->next=(p+N)->next;
                    temp->next=(p+i);
                    (p+i-1)->next=temp;
                    flag=1;
                }
            }   
        }
        /* Increase N and set i equal zero */
        if(flag==1){
            i=0;
            N++;
        }
    }
    printf("Our ordered values in the LinkedList: ");
    printLinkedList(head);
}

我的代码在特定情况下似乎运行良好。例如,如果我输入终端:

./a.out 2 1 3 1 5 4 3

一个“枢轴”工作正常,算法将“ 2”和“ 1”交换。这样我们得到:

1 2 3 1 5 4 3

然后,下一个枢轴也可以正常工作,并且算法先比较“ 1”和“ 3”,然后比较“ 2”和“ 3”,然后决定不执行任何操作,只增加“ pivot”即可。这样我们得到:

1 2 3 1 5 4 3

这时我的算法疯狂了,它比较“ 1”,“ 1”确定“ 1(第一个节点)”大于“ 1(枢轴)”。该算法的其余部分不起作用。作为最终结果,打印出的所谓“排序”数组为:

1 4

我在其他网站上看到了与通过链接列表进行插入排序有关的问题,但是它们遵循的方式与我的代码尝试执行的方式不同。如果可能的话,我只想解决此算法背后的错误。如果没有,那么我可能会像其他人一样放弃并实现代码。如果有人能以正确的心态指导我解决此问题或告诉我为什么此代码可能无法正常工作,我将不胜感激。另外,如果从根本上说错了,请告诉我...

解决方法

算法的主要问题是将链接列表结构视为数组,并尝试执行p + N等操作……实际上,链接列表不是数组,因此指向节点的指针它们没有顺序地放置在存储器中,而是分散在地址空间中,并且操作p + N并不总是指向下一个节点。因此,要遍历列表,您必须仅使用p-> next语句。

,

由于@Mykola的指导,我能够在链接列表中正确实现插入排序。我已经意识到我最大的问题之一就是没有认真处理节点的指针。相反,通过他们的参考是很大的帮助。我也意识到我没有正确遍历链表。由于进行了这些更正,因此我不得不稍微更改一下代码。另外,我试图使代码更清晰,并添加了push()函数。

我将在下面包含我的代码,这样,如果有人发现自己的情况与我的相似,则可以将其作为参考:

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

typedef struct Node node;
struct Node{
    int data;
    node* next;
};

void printList(node* head);
void push(node** head_ref,int data);
void insertionSort(node** head_ref);
void insertIntoSorted(node** sorted_ref,node* new_node);

/* Driver program that applies insertion sort to singly linked lists */
int main(int argc,char* argv[]){
    int i,sizeOfList;
    sizeOfList=argc-1;
    node *head;
    head=NULL;
 
    for(i=sizeOfList;i>0;i--){
       push(&head,atoi(argv[i]));
    }

    /* Print the linked list before the insertion sort */
    printf("Your list before the insertion sort is: ");
    printList(head);

    /* insertion sort function */
    insertionSort(&head);

    /* Print the linked list after the insertion sort */
    printf("Your list after the sort is: ");
    printList(head);

    return EXIT_SUCCESS;
}


/* Utility function that inserts a new node at the beginning of a linked list */
void push(node** head_ref,int data){
    //allocate node and fill
    node* new_node;
    new_node=(node*)malloc(sizeof(node));
    new_node->data=data;    

    //link
    new_node->next=*head_ref;
    *head_ref=new_node;
}


/* Utility function to print a linked list */
void printList(node* head){
    node* temp;
    temp=head;
    while(temp!=NULL){
        printf("%d ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}


/* Function to sort a singly linked list using insertion sort */
void insertionSort(node** head_ref){

    /* Initialize the sorted linked list */
    node* sorted;
    sorted=NULL;

    /* Traverse the given linked list and insert every node to "sorted" */
    node* current;
    current=*head_ref;
    while(current!=NULL){
        /* Store "next" for next iteration */ 
        node* next;
        next=current->next;

        /*Insert "current" into the "sorted" linked list */
        insertIntoSorted(&sorted,current);

        /* Update "current" to the next node */
        current=next;
    }
    *head_ref=sorted;
}


/* Function to insert a given node in the "sorted" linked list. Where
 * the insertion sort actually occurs.
 */ 
void insertIntoSorted(node** sorted_ref,node* new_node){
    node* current; 
    /* Special case for the head end of the "sorted" */
    if ((*sorted_ref == NULL) || ((*sorted_ref)->data >= new_node->data)) 
    { 
        new_node->next = *sorted_ref; 
        *sorted_ref = new_node; 
    }
    /* Locate the node before the point of insertion */
    else
    {
        current = *sorted_ref; 
        while ((current->next!=NULL) && (current->next->data < new_node->data)){ 
            current = current->next; 
        } 
        new_node->next = current->next; 
        current->next = new_node; 
    } 
}