说实话我什么都不懂。
您不需要将链表转换为队列。您只需用列表初始化队列的数据成员ll。
这是一个演示程序
#include <stdlib.h>
#include <stdio.h>
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
int insert( LinkedList *ll, int index, int value )
{
if ( index < 0 || index > ll->size ) return -1;
ListNode *tmp = malloc( sizeof( ListNode ) );
tmp->item = value;
if ( ll->head == NULL )
{
tmp->next = ll->head;
ll->head = tmp;
}
else
{
ListNode *current = ll->head;
while ( --index ) current = current->next;
tmp->next = current->next;
current->next = tmp;
}
++ll->size;
return 0;
}
void list_output( const LinkedList *ll )
{
for ( ListNode *current = ll->head; current != NULL; current = current->next )
{
printf( "%d ", current->item );
}
printf( "\n" );
}
typedef struct _queue
{
LinkedList ll;
} Queue;
void queue_output( const Queue *q )
{
list_output( &q->ll );
}
int main( void )
{
LinkedList lst = { 0, 0 };
const int N = 10;
for ( int i = 0; i < N; i++ ) insert( &lst, i, i );
list_output( &lst );
Queue q = { lst };
lst = ( LinkedList ) { 0, 0 };
queue_output( &q );
// call here the method that free allocated memory of the queue
return 0;
}
它的输出是
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
即队列现在是已分配节点的所有者。该列表又是空的。
这意味着您确实将列表转换为队列。
如果您的意思是将列表的元素复制到队列中(与转换操作相比,这是一个不同的操作),那么逻辑如下
以与遍历列表相同的方式遍历列表以输出其元素并为列表节点的每个数据值调用队列的方法enqueue
for ( ; head != NULL; head = head->next )
{
enqueue( que, head->x );
}
列表本身将保持不变。
如果复制操作后需要删除链表的节点,可以调用链表中执行该操作的方法。
考虑到不需要动态分配列表或队列。例如,列表的声明可能看起来像
typedef struct _linkedlist
{
int size;
ListNode *head;
} LinkedList; // You should not change the definition of LinkedList
LinkedList lst = { 0, 0 };
动态分配的是链表的节点。
同样适用于队列。
您可以通过以下方式声明队列
typedef struct _queue
{
LinkedList ll;
} Queue;
Queue q = { { 0, 0 } };
如果你有一个列表,那么将它转换为队列就足够了
q.ll = lst;
lst = ( LinkedList ) { 0, 0 };
也是这个方法
void enqueue(Queue *que, int x)
{
int counter = 0;
insert(&(que->l), counter++, x);
}
没有意义。而且队列没有数据成员l。它有数据成员ll
您需要将节点附加到队列中。所以你必须使用队列的数据成员size的值作为必须插入新元素的索引。
所以方法应该是这样的
void enqueue( Queue *que, int x )
{
insert( &que->ll, que->ll.size, x) ;
}