Insert for singly-linked list C

2019-09-19 18:47发布

问题:

I am having trouble with my insert to the front of the linked list fucntion in C

#define arrSIZE = 100;

struct listNode {
    char data[arrSIZE];
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;

void insertHead(ListNode *sPtr, char value[arrSIZE]){
    ListNode *newPtr = (ListNode *)malloc(sizeof(ListNode));
    strncpy(newPtr->data, value, arrSIZE);
    if(sPtr ==NULL){
        newPtr->nextPtr=NULL;
        sPtr = newPtr;
    }else{
        newPtr->nextPtr=sPtr;
        sPtr =newPtr;
    }
}

回答1:

I can see why. -You're setting sPtr, but sPtr is a local variable and is gone as soon as you exit insertHead. Instead, you would do this:

#define arrSIZE = 100;

struct listNode
{
    char data[arrSIZE];
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;

static ListNode *sPtr = NULL;

void insertHead(char value[arrSIZE])
{
    ListNode *newPtr = (ListNode *)malloc(sizeof(ListNode));
    strncpy(newPtr->data, value, arrSIZE);
    if(sPtr == NULL)
    {
        newPtr->nextPtr = NULL;
        sPtr = newPtr;
    }
    else
    {
        newPtr->nextPtr = sPtr;
        sPtr = newPtr;
    }
}

... Thus you now have a single linked list.

On the other hand, if you want to have more than one linked list, you'll need to add another '*' on the argument:

void insertHead(ListNode **aIOPtr , char value[arrSIZE])
{
    if(aIOPtr)
    {
        ListNode *newPtr = (ListNode *)malloc(sizeof(ListNode));
        strncpy(newPtr->data, value, arrSIZE);
        if(*aIOPtr == NULL)
        {
            newPtr->nextPtr = NULL;
            *aIOPtr = newPtr;
        }
        else
        {
            newPtr->nextPtr = sPtr;
            *aIOPtr = newPtr;
        }
    }
}