【发布时间】:2015-09-26 01:51:20
【问题描述】:
所以我遇到了问题。我知道它是什么。我只是想不出一种方法来解决它允许做什么..
首先是我的尾部插入函数
Status append(MY_QUEUE queue, int item)
{
Node_ptr temp;
Head_ptr head = (Head_ptr) queue;
//create a new node
temp = (Node_ptr)malloc(sizeof(Node));
if (temp == NULL) {
printf("malloc failed\n");
return FAILURE;
}
temp->data = item;
temp->next = NULL;
if (head->head == NULL){
head->head = temp;
}
else{
while(head->head->next) {
head->head = head->head->next;
}
head->head->next = temp;
}
return SUCCESS;
}
如你所见。这很简单。如果头节点为空。它将新节点添加到头部。如果不。它一直在移动,直到达到空值,然后添加节点。那就是问题所在。正在移动我不应该做的头节点指针。但我似乎想不出另一种方法来做到这一点。因为我传入了一个 MY_QUEUE。我将包含头文件和声明以了解它们是什么。
struct node
{
int data;
Node_ptr next;
};
struct head_node;
typedef struct head_node Head_node;
typedef Head_node *Head_ptr;
struct head_node
{
struct my_queue_public methods;
Node_ptr head;
};
void destroy(MY_QUEUE queue);
Status append(MY_QUEUE queue, int item);
Status service(MY_QUEUE queue);
int* front(MY_QUEUE queue);
Bool empty(MY_QUEUE stack);
void init_functions(MY_QUEUE queue)
{
//queue->destroy = destroy;
queue->empty = empty;
queue->service = service ;
queue->append = append;
queue->front = front;
}
MY_QUEUE my_queue_init_default(void)
{
Head_ptr head;
head = malloc(sizeof(Head_node));
if (head != NULL)
{
head->head = NULL;
init_functions((MY_QUEUE)head);
}
return (MY_QUEUE)head;
}
插入尾部函数是追加函数。我无法更改我的参数或我返回的内容。我只需要更改函数内部的内容。
MY_QUEUE 是 struct Node 的公共版本。
这是头文件
#include "status.h"
struct my_queue_public;
typedef struct my_queue_public* MY_QUEUE;
struct my_queue_public
{
void(*destroy)(MY_QUEUE* phMy_queue);
Status(*service)(MY_QUEUE hMy_queue);
Status(*append)(MY_QUEUE hMy_queue, int item);
Bool(*empty)(MY_QUEUE hMy_queue);
int* (*front)(MY_QUEUE hMy_queue);
};
MY_QUEUE my_queue_init_default(void);
顺便说一句,这是一个队列。最后添加。从前面获取物品。总而言之,头部正在移动,我失去了节点。我知道如何避免它,但我知道的唯一方法是更改我传入的内容。而不是 MY_QUEUE。我会通过一个 MY_QUEUE*。有没有另一种方法可以用我所拥有的来做到这一点
销毁函数
void destroy(MY_QUEUE queue)
{
Head_ptr head = (Head_ptr)queue;
Node_ptr tmp;
if (head->head == NULL) {
return;
}
while (head->head !=NULL){
tmp = head->head;
head->head = head->head->next;
free(tmp);
}
head->head = NULL;
}
【问题讨论】:
-
有无数的链表实现运行良好;为什么要自己写?或者,如果您真的想/需要自己编写,为什么不看看现有的实现之一?
-
我没有自己写这是我老师给我的,所以我必须使用这个骨架。
-
将
head存储在一个临时的head_ptr中并使用它。 -
^ 你意识到我已经这样做了
标签: c linked-list queue