所以今天早些时候我发布了我遇到的分段错误的链接:分段错误错误 - 使用链接列表实现堆栈
我得到的答案非常棒,我在给出的答案之后摆脱了错误......但后来它又回来了。
这是我的新代码(我添加到 main()):
#include <stdio.h>
#include <stdlib.h>
typedef struct Link{
int value;
struct Link *next;
}Link;
typedef struct LList1{
int size;
Link *head;
}LList1;
typedef struct LListStack{
LList1 *llist;
}LListStack ;
LListStack *initLListStack(void)
{
LListStack *stack = (LListStack *) malloc(sizeof(LListStack)) ;
stack->llist = (LList1 *) malloc (sizeof(LList1));
stack->llist->size = 0;
stack->llist->head = NULL;
return(stack);
}
void removefront(LList1 *llist)
{
if(llist->head != NULL){
llist->head = llist->head->next;
llist->size--;
}
}
Link *FindLastLink(LList1 *llist, Link *link)
{
if(link = NULL){
return(NULL);
}
else if(link->next == NULL){
return(link);
}
else{
return(FindLastLink(llist, link->next));
}
}
Link *FindSecondLastLink(LList1 *llist, Link *link)
{
if(link = NULL){
return(NULL);
}
else if(link->next->next == NULL){
return(link);
}
else{
return(FindSecondLastLink(llist, link->next));
}
}
void removelast(LList1 *llist)
{
Link *secondlastlink = (Link *) malloc(sizeof(Link));
secondlastlink = FindSecondLastLink(llist, llist->head);
secondlastlink->next = NULL;
llist->size--;
}
void prepend(int newValue, LList1 *templist)
{
Link *node = (Link *) malloc(sizeof(Link));
node->value = newValue;
node->next = templist->head;
templist->head = node;
templist->size++;
}
void append(int newValue, LList1 *templist)
{
Link *node = (Link *) malloc(sizeof(Link));
Link *lastlink = (Link *) malloc(sizeof(Link));
lastlink = FindLastLink(templist, templist->head);
node->value = newValue;
lastlink->next = node;
node->next = NULL;
templist->size++;
}
void prepush(int value, LListStack *stack)
{
prepend(value, stack->llist);
}
void apppush(int value, LListStack *stack)
{
append(value, stack-> llist);
}
int prepop(LListStack *stack)
{
int result ;
if ((!isEmpty(stack)))
{
removefront(stack->llist);
result = 1 ;
}
else {
result = 0 ;
}
return(result) ;
}
int isEmpty(LListStack *stack)
{
int empty;
if (stack->llist->head == NULL)
return( 1 ) ;
else
return( 0 ) ;
}
int apppop(LListStack *stack)
{
int result ;
if ((!isEmpty(stack)))
{
removelast(stack->llist);
result = 1 ;
}
else
result = 0 ;
return(result) ;
}
void PrintList(LList1 *llist, Link *link){
if (link->next != NULL){
printf("%d \n", link->value);
PrintList(llist, link->next);
}
}
//*******MAIN**********//
int main()
{
LListStack *stack = (LListStack *) malloc (sizeof(LListStack));
stack = initLListStack(); //if I take this away, I can run the program
int pre, app, i, n=10;
for(i=0;i<10;i++){
prepush(i, stack);
}
app = apppop(stack); //this cause a segmentation fault
for(i=4;i>0;i--){
apppush(i, stack); //so does this
prepush(i, stack);
}
PrintList(stack->llist, stack->llist->head);
return(0);
}
现在查看 main(),当我调用“prepush()”或“prepull()”时,一切正常。但是,如果我调用“apppush()”或“apppull()”,则会出现分段错误。跟踪函数让我相信罪魁祸首是函数FindLastLink()
,FindSecondLastLink()
特别是因为它们都包含递归。我不知道为什么,因为我对此很陌生,所以任何解决这个问题的帮助都会很棒。
再次感谢各位!