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

如何解决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; 
    } 
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-