将链表转换为队列(移动节点)

标签 c pointers linked-list queue

我需要一些逻辑方面的帮助,我需要从链表创建队列。所以我从问题中得到了所有这些代码:

typedef struct _listnode
{
    int item;
    struct _listnode *next;
} ListNode; // You should not change the definition of ListNode

typedef struct _linkedlist
{
    int size;
    ListNode *head;
} LinkedList;   // You should not change the definition of LinkedList

typedef struct _queue
{
    LinkedList ll;
} Queue;

并且通过使用 enqueue、dequeue 和 isEmptyQueue,我应该从链表创建一个队列。

所以我得到的逻辑是:

 Loop thru list size
      enqueue linked list head node
      removeNode to update linkedlist head node

这个逻辑对吗?我需要先行一步,在此先致谢。

所以我想出了这段代码来从链表创建队列:

但是,它使我的程序崩溃并且没有错误消息。我尝试使用虚拟值 enqueue(q,1) 但它仍然崩溃。有什么想法吗?

最佳答案

我认为你的逻辑是正确的,但我会添加更多细节以使其更容易编码

Loop through the link list, selecting nodes one by one (until NULL)
    select a node;
    enqueue the value to the queue;
    Free the memory of that enqueued node;
    adjust the pointers to point to the next node in the linked list;

编辑

让我们详细写一下算法

while(head != NULL)
//Loop to traverse the linked list, just as you would while displaying each node

    enqueue( que, head->item);
    //This function will work just like a normal enqueue() function
    //It should take the item, and insert it in the queue and nothing else
    //I would recommend use an array for the queue

    temp = head;          //save the current node address to free later
    head = head -> next;  //go to next node in the linked list
    free(temp);           //free the previous node

关于将链表转换为队列(移动节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33449623/

相关文章:

c++ - 如何增加字符指针?

c++ - C++中的多线程链表

java - 根据用户输入的数字循环初始化新对象

c - 动态链接库相互依赖时的链接顺序问题

c - 编译 uboot 时出现“input in Flex Scanner failed”错误

c - x86 从数据中分辨指令的方法

c - 为结构指针执行 malloc 时出现段错误

c - 如何在字符数组C中使用正则表达式

c++ - C++中指针的地址

c++ - 创建对象的链接列表