Insert for singly-linked list C

徘徊边缘 提交于 2019-12-25 18:23:20

问题


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;
        }
    }
}


来源:https://stackoverflow.com/questions/26834117/insert-for-singly-linked-list-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!