我想在C中設置一個雙向指針隊列。 到目前爲止,我有推送功能的工作和測試。我的問題似乎是在兩端彈出條目。指針出隊 - 指針訓練
#include <stdlib.h>
#include <stdio.h>
#include "dequeue.h"
dequeue* dequeue_create()
{
return NULL;
}
void dequeue_push_front(dequeue** dq, int data)
{
dequeue* tmp = malloc(sizeof(*tmp));
tmp->data = data;
tmp->next=NULL;
if((*dq) == NULL)
{
(*dq) = tmp;
}
else
{
if ((*dq)->next == NULL)
{
(*dq)->next = tmp;
tmp->prev = (*dq);
}
else
{
dequeue* tmp_it = malloc(sizeof(struct _dequeue_));
tmp_it = (*dq)->next;
while(tmp_it->next != NULL)
{
tmp_it = tmp_it->next;
}
tmp_it->next = tmp;
tmp->prev = tmp_it;
}
}
}
void dequeue_push_back(dequeue** dq, int data)
{
dequeue* tmp = malloc(sizeof(struct _dequeue_));
tmp->data = data;
tmp->prev=NULL;
if((*dq) == NULL)
{
(*dq) = tmp;
}
else
{
if ((*dq)->prev == NULL)
{
(*dq)->prev = tmp;
tmp->next = (*dq);
}
else
{
dequeue* tmp_it = malloc(sizeof(struct _dequeue_));
tmp_it = (*dq)->prev;
while(tmp_it->prev != NULL)
{
tmp_it = tmp_it->prev;
}
tmp_it->prev = tmp;
tmp->next = tmp_it;
}
}
}
int dequeue_pop_front(dequeue** dq)
{
dequeue* tmp_get = malloc(sizeof(struct _dequeue_));
int output = 0;
if((*dq)->next == NULL)
{
printf("\ndqnext==null\n");
}
else
{
tmp_get = (*dq);
while(tmp_get->next != NULL)
{
tmp_get= tmp_get->next;
output = tmp_get->data;
}
tmp_get=tmp_get->prev;
free(tmp_get->next);
tmp_get->next=NULL;
}
return output;
}
int dequeue_pop_back(dequeue** dq)
{
dequeue* tmp_get = malloc(sizeof(struct _dequeue_));
int output = 0;
if((*dq)->prev == NULL)
{
printf("\ndqprev==null\n");
}
else
{
tmp_get = (*dq);
while(tmp_get->prev != NULL)
{
output = tmp_get->data;
tmp_get= tmp_get->prev;
}
free(tmp_get);
tmp_get=NULL;
}
return output;
}
dequeue.h:
#ifndef dequeue_H
#define dequeue_H
struct _dequeue_ {
struct _dequeue_* next;
struct _dequeue_* prev;
int data;
};
typedef struct _dequeue_ dequeue;
dequeue* dequeue_create();
void dequeue_destroy(dequeue** queue);
int dequeue_pop_front(dequeue** dq);
void dequeue_push_front(dequeue** dq, int data);
int dequeue_pop_back(dequeue** dq);
void dequeue_push_back(dequeue** dq, int data);
#endif /* dequeue_H */
的main.c:
int main()
{
dequeue* dq = dequeue_create();
dequeue_push_front(&dq, 1);
dequeue_push_back(&dq, 2);
dequeue_push_front(&dq, 3);
for (int cnt = 1; cnt <=4; cnt++)
{
printf("FINAL=%d ", dequeue_pop_front(&dq));
}
//TODO : dequeue_destroy(&dq);
return 0;
}
我非常新的指針,這似乎是我的問題。
我想在彈出函數中做的是遍歷指針到達最後一個指針並釋放最後一個指針。但它似乎並沒有釋放指針。現在嘗試了幾種不同的方式,但似乎沒有一個能夠工作,難道我設置推送功能的方式不可能釋放指針嗎?
任何幫助非常感謝。 歡呼聲
我不明白你爲什麼要在pop裏面調用'malloc()'。這會導致代碼中的內存泄漏。 – zapstar
我想過使用tmp_get作爲tmp指針。修正了這個錯誤* tmp_get =(* dq);並在elses中刪除它。 –
upvote for(almost)http://stackoverflow.com/help/mcve –