博客
关于我
链队列——出入队列
阅读量:297 次
发布时间:2019-03-03

本文共 1077 字,大约阅读时间需要 3 分钟。

队列数据结构实现

队列是一种先进先出的数据结构,可以通过两端操作数据。在本次实现中,我们使用两个结构体分别存储队列的头和尾节点。

结构体定义如下:

```cstruct node { int data; node *next; };

struct Queue

{
node *head; // 表头指针
node *rear; // 尾部指针
};

Queue Q; // 队列对象

初始化队列时,默认将头节点和尾节点初始化为一个空节点:

```cQ.head = new node; Q.rear = new node; Q.head->next = NULL; Q.rear->next = NULL;

实现队列的增操作(get_link函数):

```cvoid get_link(int x, Queue *Q) { node *tail = Q.rear; // 获取当前尾部节点
while (x--)  {      node *q = new node;      scanf("%d", &q->data);      tail->next = q;      q->next = NULL;      tail = q;  }  Q.rear = tail;  // 更新尾部指针

实现队列的删操作(out_link函数):

```cvoid out_link(node *head) { node *q = head->next; while (q) { printf("%d\n", q->data); q = q->next; } head->next = q; // 将原头节点的下一个指针设为空节点

主函数实现:

```cint main() { int x; scanf("%d", &x);
node *head = new node;  Q.head = Q.rear = head;  // 初始化头和尾都指向同一个空节点  get_link(x, &Q);  // 读取并添加x个节点  out_link(Q.head);  // 输出队列中的数据  if (!Q.head->next)  {      printf("队列为空\n");  }  return 0;

}

整个实现通过动态分配节点实现了队列的基本操作,支持插入和删除数据。通过尾部指针的更新确保了队列的高效操作。

转载地址:http://oqsl.baihongyu.com/

你可能感兴趣的文章
Objective-C实现ExponentialSearch指数搜索算法(附完整源码)
查看>>
Objective-C实现extended euclidean algorithm扩展欧几里得算法(附完整源码)
查看>>
Objective-C实现ExtendedEuclidean扩展欧几里德GCD算法(附完整源码)
查看>>
Objective-C实现external sort外排序算法(附完整源码)
查看>>
Objective-C实现Factorial digit sum阶乘数字和算法(附完整源码)
查看>>
Objective-C实现factorial iterative阶乘迭代算法(附完整源码)
查看>>
Objective-C实现factorial recursive阶乘递归算法(附完整源码)
查看>>
Objective-C实现factorial阶乘算法(附完整源码)
查看>>
Objective-C实现factorial阶乘算法(附完整源码)
查看>>
Objective-C实现Factors因数算法(附完整源码)
查看>>
Objective-C实现Farey Approximation近似算法(附完整源码)
查看>>
Objective-C实现Fast Powering算法(附完整源码)
查看>>
Objective-C实现Fedwick树算法(附完整源码)
查看>>
Objective-C实现fenwick tree芬威克树算法(附完整源码)
查看>>
Objective-C实现FenwickTree芬威克树算法(附完整源码)
查看>>
Objective-C实现fermat little theorem费马小定理算法(附完整源码)
查看>>
Objective-C实现FermatPrimalityTest费马素数测试算法(附完整源码)
查看>>
Objective-C实现fft2函数功能(附完整源码)
查看>>
Objective-C实现FFT快速傅立叶变换算法(附完整源码)
查看>>
Objective-C实现FFT算法(附完整源码)
查看>>