我想创建一个堆栈,但我想保留类似头指针的链表实现。我的意思是正面对反面。
void insertCustomer(CustomerPtr *headPtr, int id, char name[20], char surname[20]){
CustomerPtr newPtr = (CustomerPtr)malloc(sizeof(Customer));
newPtr->customerId = id;
strcpy(newPtr->customerName, name);
strcpy(newPtr->customerSurname, surname);
CustomerPtr previousPtr, currentPtr;
previousPtr = NULL;
currentPtr = *headPtr;
while(currentPtr != NULL){
previousPtr = currentPtr;
currentPtr = currentPtr->next;
}
if(previousPtr == NULL){
*headPtr = newPtr;
} else{
previousPtr->next = newPtr;
}
}
我有一个分割错误。
您似乎忘记初始化newPtr->next
了。通过malloc()
分配的区域的初始值是不确定的,使用不确定的值会调用未定义的行为。
void insertCustomer(CustomerPtr *headPtr, int id, char name[20], char surname[20]){
CustomerPtr newPtr = (CustomerPtr)malloc(sizeof(Customer));
newPtr->customerId = id;
strcpy(newPtr->customerName, name);
strcpy(newPtr->customerSurname, surname);
newPtr->next = NULL; /* add this */
CustomerPtr previousPtr, currentPtr;
/* ... */
如果目标是使用链表实现堆栈,那么insert|push需要在列表的开头插入新节点,而不是将其附加到列表的末尾,remove|pop需要删除列表的第一个节点。像这样的插件:
CustomerPtr newPtr = (CustomerPtr)malloc(sizeof(Customer));
newPtr->customerId = id;
strcpy(newPtr->customerName, name);
strcpy(newPtr->customerSurname, surname);
newPtr->next = *headPtr;
*headPtr = newPtr;