c - 在不交换数据的情况下交换链表中的节点

标签 c sorting linked-list bubble-sort

如何在不复制数据的情况下使用指针? 我想写一个冒泡排序函数,但我卡住了,需要一些帮助来交换节点地址而不是值。 我有一个包含城市名称和温度的文件:

  • 拉斯维加斯,25 岁​​
  • 纽约,33 岁
  • 芝加哥,23 岁
  • 休斯顿,39 岁

我需要按温度排序,并将其写入另一个文件。

更新: 好的,现在我想我理解了理论部分:

// p is my node
// p-prev -> p -> p-next -> p-next-next
prev->next = p->next;
p->next = p->next->next;
prev->next->next = p;

这是我需要做的,交换节点,但在语法上我无法让它工作。

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

struct node {
    char name[128];
    int id;
    struct node *next;
}*head;

void readFile() {
    char fnamer[128] = "";
    printf("\nEnter the file name to read (delimiter: ,): \n");
    scanf("%s",&fnamer);
    FILE *inf = fopen(fnamer, "r");

    char buffer[1024];
    memset(buffer, 0, 1024);
    while(fgets(buffer, 1024, inf)){
        struct node *temp = malloc(sizeof(struct node));
        temp->next = NULL;

        if(sscanf(buffer, "%19[^,], %d", temp->name, &temp->id) != 2){
            free(temp);
            break;
        }

        if(!head){
            head = temp;
        } else{
            temp->next = head;
            head = temp;
        }
    }

    fclose(inf);
}

int main(void) {
    // Read a linked list from file
    readFile();

    //Bubble sort in linked list
    struct node *loop1 = head;
    while(loop1){
        struct node *loop2 = loop1->next;
        while(loop2){
            if(loop1->id > loop2->id){

                // Swap next pointers
                // This is not working
                struct node *temp = loop1->next;
                loop1->next = loop2->next;
                loop2->next  = temp;

            }
            loop2 = loop2->next;
        }
        loop1 = loop1->next;
    }

    // Print the sorted linked list to file:
    char foutname[100]="";
    printf("\nPlease Enter the file name to write the result: \n");
    scanf("%s",&foutname);

    FILE *outf;
    outf = fopen(foutname, "w+");

    loop1 = head;
    while(loop1){
        printf("%s %d\n", loop1->name, loop1->id);
        fprintf(outf, "%s %d\n", loop1->name, loop1->id);
        loop1 = loop1->next;
    }
    fclose(outf);
    return 0;
}

最佳答案

要交换单链表中的两个节点,您可以使用以下函数

void swap(struct node **current)
{
    struct node *tmp = (*current)->next->next;
    (*current)->next->next = *current;
    *current = (*current)->next;
    (*current)->next->next = tmp;
}

例如,要交换头节点和下一个节点,您可以调用如下函数

swap( &head );

另请参阅我在此引用中的回答 Bubble sort in c linked list其中展示了如何为单链表编写冒泡排序算法。

关于c - 在不交换数据的情况下交换链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47761941/

相关文章:

c链表删除函数

Java 程序读取文本文件并将其与用户输入进行比较

c - 从链表中给定位置删除一个元素

C : Printing a pointer to an array seems to print a junk value also

c++ - 在其他相同的数组旁边排序数组

php - 多个值的哈希方法?

c - 将数组发送到函数仅发送数组的第一个元素

c - 在 Linux 上以相反顺序接收的实时信号

c - 将数据存储在程序中而不是外部文件中

c++ - 如何使用 C/C++ 创建 linux 用户?