![](/img/trans.png)
[英]C - Linked list implementation of Stack, having trouble with pop() function?
[英]C Program, having trouble traversing singly linked list for pop function
我正在嘗試制作一個可以通過推,彈出和完整功能訪問的鏈表。 我相信我已經正確創建了push函數,但是在實現pop時遇到了麻煩。 我想我已經找到了錯誤,我無法使用while循環遍歷鏈接列表。
這是我的推送功能:
int push(char x){
if(full() == 1) return 1;
else if(full() == 0){
last = malloc(sizeof(struct Node));
aNode = malloc(sizeof(struct Node));
aNode -> next = anchor;
anchor = aNode;
aNode -> data = x;
last -> data = aNode -> data;
last -> next = aNode -> next;
return 0;
}
else{
aNode = malloc(sizeof(struct Node));
aNode -> next = anchor;
anchor = aNode;
aNode -> data = x;
last -> data = aNode -> data;
last -> next = aNode -> next;
return 0;
}
我的彈出功能是:
int pop(){
if(full() == 0) return 0;
else{
curr_ptr = malloc(sizeof(struct Node));
store = malloc(sizeof(struct Node));
curr_ptr = anchor;
while(curr_ptr != NULL){
curr_ptr = curr_ptr -> next;
}
store -> next = '\0';
store -> data = last -> data;
last -> next = curr_ptr -> next;
last -> data = curr_ptr -> data;
free(curr_ptr);
return store -> data;
}
我在while循環中遇到分段錯誤。 我嘗試了一個備用while循環,該循環沒有引起任何錯誤,但是由於某種原因從未在代碼中執行。 我在循環中拋出了一個printf語句,但它從未打印任何內容。 那個循環是:
while(curr_ptr -> next != NULL){
curr_ptr = curr_ptr -> next;
}
您永遠不會分配pop
last
,但要為其循環。 用for (last=anchor; last->next; last=last->next);
替換您的while(curr_ptr/*...*/
循環for (last=anchor; last->next; last=last->next);
自動跳到last
一個列表成員,但是您的double-free來自
curr_ptr = anchor;
/* ... */
free(curr_ptr);
而curr_ptr
不指向malloc
版的內存,但到anchor
,這是你的名單很可能部分,不應該被釋放。 正如Mike所說的,curr_ptr應該只在指向列表時分配內存。 實際上,沒有理由在pop
函數中分配任何東西!
編輯評論:根據您的示例,作為有關列表結構的示例
struct Node {
char data;
struct Node* next;
};
struct List {
struct Node* head;
struct Node* tail;
};
int push(struct List* L, char c);
int pop(struct List* L);
接下來,您可以基本定義您的函數(可能意味着滿功能)。
int push(struct List* L, char c)
{
if (L->head == NULL) {
L->head = L->tail = malloc(sizeof(struct Node));
L->head->data = x;
} else {
L->tail->next = malloc(sizeof(struct Node));
L->tail = L->tail->next;
L->tail->data = x;
}
return 1;
}
int pop(struct List* L)
{
struct Node* cur = NULL;
if (L->head == NULL) {
return 0; /* nothing to remove */
} else if (L->head == L->tail) {
free(L->head);
L->head = L->tail = NULL; /* the list is empty now */
} else {
for (cur = L->head; cur->next != L->tail; cur = cur->next);
cur->next = NULL;
free(L->tail);
L->tail = cur;
}
return 1;
}
現在,您可以開始專門滿足您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.