问题
I'm trying to construct a simple Linked List but I get a compile error telling me the Linked List node I'm trying to access doesn't contain the field I expect it to. These are my Linked List methods:
typedef struct TinCan
{
int label;
} TinCan;
typedef struct LinkedListNode
{
TinCan *data;
struct LinkedListNode *next;
} LinkedListNode;
typedef struct LinkedList
{
LinkedListNode *head;
} LinkedList;
LinkedList* createList() /*creates empty linked list*/
{
LinkedList* myList;
myList = (LinkedList*)malloc(sizeof(LinkedList));
myList->head = NULL;
}
I malloc a struct and send it to the list like so:
LinkedList* canQueue=createList();
TinCan* testCan = (TinCan*) malloc(sizeof(TinCan));
testProc->pid=69;
insertLast(canQueue, testCan);
void insertLast(LinkedList* list, ProcessActivity *newData)
{
int ii = 1;
LinkedListNode* newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
newNode->data = newData;
//check if queue empty
if(list->head == NULL)
{
list->head = newNode;
newNode->next=NULL;
}
else
{
LinkedListNode* current = list->head;
while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
printf("%d", ii);
ii++;
}
}
And then I try to acess the node like so:
testLinkedList(cpuQueue);
void testLinkedList(LinkedList* list)
{
int count = 1;
LinkedListNode* current = list->head;
while (current != NULL)
{
printf("%d: Label is is %d", count, current->data->label);
current = current->next;
count++;
}
}
The compile error shows up for the last method: 'LinkedListNode' has no member named 'label'. I can't see where I've gone wrong, can someone identify a problem with the code?
回答1:
TinCan doesn't have field pid
Maybe:
testProc->label=69;
instead of
testProc->pid=69;
回答2:
LinkedList* createList() /*creates empty linked list*/
{
LinkedList* myList;
myList = (LinkedList*)malloc(sizeof(LinkedList));
myList->head = NULL;
--> return myList;
}
来源:https://stackoverflow.com/questions/16331530/simple-linked-list-not-able-to-access-nodes