簡體   English   中英

如何交換C中鏈表節點的char值?

[英]How to swap char value of nodes of linkedlist in C?

我正在嘗試根據我在 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); 
} 

/* function 交換兩個節點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 function 從 char 數組中獲取 int 值。 atoi function 幫我從“頻率”數組中獲取整數值但我不知道如何用 b-> 頻率值更改a->頻率值。

任何幫助將不勝感激在此先感謝

最簡單的解決方案是使用字符串之一或 memory 從庫中復制函數:

#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成員包含一個以空值結尾的字符串。 無論空終止如何,您都可以使用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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM