【问题标题】:How to swap char value of nodes of linkedlist in C?如何在C中交换链表节点的char值?
【发布时间】:2021-03-15 15:56:32
【问题描述】:

我正在尝试根据我在 char 数组中保存的 int 值对链表进行冒泡排序。 我知道我需要执行以下步骤;

void bubbleSort(struct Node *start) 
{ 
    int swapped, i; 
    struct Node *ptr1; 
    struct Node *lptr = NULL; 
  
    /* Checking for empty list */
    if (start == NULL) 
        return; 
  
    do
    { 
        swapped = 0; 
        ptr1 = start; 
  
        while (ptr1->next != lptr) 
        { 
            if (ptr1->data > ptr1->next->data) 
            {  
                swap(ptr1, ptr1->next); 
                swapped = 1; 
            } 
            ptr1 = ptr1->next; 
        } 
        lptr = ptr1; 
    } 
    while (swapped); 
} 

/*函数交换两个节点a和b的数据*/

{ 
    int temp = a->data; 
    a->data = b->data; 
    b->data = temp; 
} 

但正如我上面所说,我创建了一个具有 char 值的结构;

struct nodeForLinkedList
{
    char frequency[STRING_LEN]; **// Purpose of this is to hold int value from text file.**
    struct nodeForLinkedList *next;
}; 
void swap(struct nodeForLinkedList *a, struct nodeForLinkedList *b) 
{ 
    char temp = a->frequency; 
    a->frequency = b->frequency; //  atoi(b->frequency) or strtol
    b->frequency = temp; 
}

在这里我可以使用 atoi 函数从 char 数组中获取 int 值。 atoi 函数帮助我从“频率”数组中获取 int 值 但我不知道如何将 a->frequency 值更改为 b->frequency 值。

任何帮助将不胜感激 提前致谢

【问题讨论】:

    标签: arrays c linked-list char swap


    【解决方案1】:

    最简单的解决方案是使用库中的字符串或内存复制函数之一:

    #include <string.h>
    
    void swap(struct nodeForLinkedList *a, struct nodeForLinkedList *b) 
    { 
        char temp[sizeof(a->frequency)];
        strcpy(temp, a->frequency);
        strcpy(a->frequency, b->frequency);
        strcpy(b->frequency, temp);
    }
    

    上面对strcpy 的使用假定frequency 成员包含一个以null 结尾的字符串。您可以使用memcpy 复制整个数组,而不管空终止:

    #include <string.h>
    
    void swap(struct nodeForLinkedList *a, struct nodeForLinkedList *b) 
    { 
        char temp[sizeof(a->frequency)];
        memcpy(temp, a->frequency, sizeof(temp));
        memcpy(a->frequency, b->frequency, sizeof(temp));
        memcpy(b->frequency, temp, sizeof(temp));
    }
    

    【讨论】:

    • 谢谢,帮了大忙。
    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2018-11-05
    • 1970-01-01
    相关资源
    最近更新 更多