我對 C 很陌生,剛開始學習鏈表。我正在嘗試用 c 設計一個鏈表結構,并且想知道如何向我的 LL 添加字母。過去對于整數,我只是使用了一個帶有 i 的 for 回圈,并在它遞增時將數字 i 添加到 LL 中。我怎么能用字母做同樣的事情,比如 A、B、C?是否涉及使用 ASCII?我在網上搜索,發現 A 的 ASCII 是 65 并且想知道我是否可以以某種方式列印 ASCII ......下面是一個嘗試。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct node
{
void* dataPtr;
struct node* next;
} NODE;
typedef struct
{
NODE* head;
int count;
} LIST;
NODE* createNode (void* itemPtr)
{
NODE* nodePtr;
nodePtr = (NODE*) malloc (sizeof (NODE));
nodePtr->dataPtr = itemPtr;
nodePtr->next = NULL;
return nodePtr;
}
LIST* createList(void)
{
LIST* list;
list= (LIST*) malloc (sizeof (LIST));
if (list)
{
list->head = NULL;
list->count = 0;
}
return list;
}
bool insertList (LIST* list, void* itemPtr)
{
NODE* newPtr;
if (!(newPtr = (NODE*)malloc(sizeof(NODE)))) return false;
newPtr->dataPtr = itemPtr;
newPtr->next = list->head;
(list->count) ;
list->head = newPtr;
return true;
}
int main (void)
{
char* newDataP;
LIST* sList;
sList = createList();
for (int i = 1; i<=26; i ){
newDataP = (char*) malloc (sizeof(int));
*newDataP = 64 i;
insertList (sList, newDataP);
}
//print out the chars, I'm trying to do the 26 capitalized letters, which is why
//I started at 64
return 0;
}
uj5u.com熱心網友回復:
您的代碼似乎將字母正確存盤到鏈表中。所以你可能用 printf("%d", var) 列印變數。在 C 中,char 是整數,所以如果你想列印一個字符,你應該使用 printf("%c", var)
如果你想改進你的代碼,你應該使用(char*)malloc(sizeof(char)). 而不是寫,64你可以直接寫'A',因為'A'ASCII 中 A 的值是 64
uj5u.com熱心網友回復:
您對void指標的使用使我假設您正在嘗試制作一些通用鏈表。你可以這樣做,但它通常比在 C 中更麻煩。所以,如果你只想要一個特定型別的串列,你通常最好為該型別創建一個特定的資料結構。如果使用void *,則必須使用指標,這涉及大量記憶體管理,幾乎所有型別檢查都會丟失,而且我通常認為在 95% 的情況下不值得這樣做。
如果您只想char作為鏈接中的資料,請使用char. 然后,它很少。
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct node
{
char data; // Use an actual char for the data
struct node *next;
};
// Unless you really need the count (it is rare that you do),
// then you don't need a list structure. You can use a link as
// the head of a list and get all of the same benefits. But here
// is a list.
struct list
{
struct node *data;
int count;
};
// For initialising a list, we just need to set data to NULL
// and count to zero, so we might as well return a struct.
// notice: doesn't return a pointer
struct list
newList(void)
{
return (struct list){.data = NULL, .count = 0};
}
struct node *
createNode(char data, struct node *next)
{
struct node *node = malloc(sizeof *node);
assert(node); // handle alloc failures
*node = (struct node){.data = data, .next = next};
return node;
}
bool insertList(struct list *list, char data)
{
list->data = createNode(data, list->data);
list->count ;
return true;
}
int main(void)
{
struct list list = newList();
const char *some_data = "abcdABCD";
for (const char *c = some_data; *c; c )
{
insertList(&list, *c);
}
// insert prepends, so the data is reversed compared
// to some_data.
for (struct node *n = list.data; n; n = n->next)
{
printf("looking at %c\n", n->data);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359879.html
