【问题标题】:Insertion Sort for Singly Linked List in CC中单链表的插入排序
【发布时间】:2020-12-11 17:45:13
【问题描述】:

我正在努力提高我对算法和数据结构的了解,因此在过去的 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,node *head,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”,它决定什么都不做,只是增加“枢轴”。所以我们得到:

1 2 3 1 5 4 3

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

1 4

我在其他网站上看到了与使用链表进行插入排序相关的问题,但是它们采用的方法与我的代码尝试执行的方法不同。如果可能的话,我只想解决这个算法背后的错误。如果没有,那么我可能会像其他人一样放弃并实现代码。如果有人能以正确的心态指导我解决这个问题,或者告诉我为什么这段代码可能不起作用,我将不胜感激。另外,如果这方面有什么根本上的错误,请告诉我...

【问题讨论】:

  • 另外澄清一下:通常在插入排序中,枢轴与之前的元素反复比较,直到找到合适的位置。在我的算法中,我从列表的开头比较我的枢轴(因为使用的数据结构是单链表),而不是检查 (pivot-1) th 元素,然后是 (pivot-2) th 元素,等等on... 这种情况是否仍被视为一种“插入排序”,或者由于我更改了“遍历方法”,它现在是一种不同的排序算法?

标签: c sorting data-structures linked-list insertion-sort


【解决方案1】:

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

【讨论】:

  • @tamuno 这可能发生在一个又一个调用 malloc 时,但是如果操作系统确定当前内存页面已满等,它可能会使用来自另一个页面的地址,而不是新的地址编号会很远从先前分配的地址。您的代码中的问题显然在于这种不需要节点地址的指针操作。这个算法实现起来非常简单,我建议重写它,这样它会更清晰,更“漂亮”。
  • 下面我描述了链表实现的一些关键点:
  • 1) 插入函数应该接受指向头部的双指针,以便在新元素小于当前头部时替换它。
  • 2) 不需要传递当前列表大小,因为无论如何都必须迭代整个列表。空列表是 head = NULL 的列表
  • 3) 迭代非常简单,因为 node* iter = head; while(iter) { /* 做一些工作 */ iter=iter->next;} 如果我们遇到尾巴,我们将停止,因为它有 next = NULL
【解决方案2】:

感谢@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; 
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 2017-10-23
    • 1970-01-01
    • 2013-04-04
    • 2012-12-29
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多