zoukankan      html  css  js  c++  java
  • 队列--双链表实现

    队列是一种常见的数据结构。常用于buffer数据,因为他是先进先出,先来的数据先消耗。

    最常用的操作是插入队列尾部,和读取头部数据。

    通常在项目中,一个线程来buffer数据,另外一个线程来消耗数据。

    下面给出队列的常用方法,并写一个简单的验证程序。

    #include <stdlib.h>
    #include <stdio.h>
    typedef struct _ListNode{
      struct _ListNode *prev;
      struct _ListNode *next;
      int data;
    }ListNode;
    typedef struct _List{
      ListNode *head;
      ListNode *tail;
      int len;
    }List;
    void list_init(List *pList)
    {
      pList->head = NULL;
      pList->tail = NULL;
      pList->len = 0;
    }
    void list_insert_tail(List *pList, ListNode *node)
    {
      node->next = NULL;
      if ((node->prev = pList->tail) != NULL)
      {
        pList->tail->next = node;
      }
      else
      {
        pList->head = node;
      }
      pList->tail = node;
      pList->len++;
    }
    void list_remove(List *pList, ListNode* node)
    {
      if (pList->tail == node)
      {
        pList->tail = node->prev;
      }
      else
      {
        node->next->prev = node->prev;
      }
      if (pList->head == node)
      {
        pList->head = node->next;
      }
      else
      {
        node->prev->next = node->next;
      }
      if (node != NULL)
      {
        node->prev = node->next = NULL;
      }
    }
    int main(void)
    {
      List _list;
      ListNode *pListNode;
      list_init(&_list);
      int idx = 0;
      for (idx = 0; idx < 10; idx++)
      {
        pListNode = (ListNode*)malloc(sizeof(ListNode));
        pListNode->data = idx;
        pListNode->prev = NULL;
        pListNode->next = NULL;
        list_insert_tail(&_list,pListNode);
      }
      ListNode *tmp;
      printf("head:%d, tail:%d, len:%d ", _list.head->data, _list.tail->data,_list.len);
      for (tmp = _list.head; tmp != NULL; tmp = tmp->next)
      {
        printf("list node:%d ", tmp->data);
      }
      for (idx = 0; idx < 10; idx++)
      //for (tmp = _list.head; tmp != _list.tail; tmp = tmp->next)
      {
        tmp = _list.head;
        printf("remove list head:%d ", _list.head->data);
        list_remove(&_list, tmp);
      }

      return 0;
    }

    运行结果如下:

  • 相关阅读:
    [HNOI2008]神奇的国度(最大势算法)
    学习笔记——prufer序列
    [NOIP模拟题]chess(最短路计数)
    2019暑假图论总结
    [NOIP2016]天天爱跑步(桶)
    [NOIP2012]疫情控制(贪心)
    [NOIP2016]蚯蚓(单调性乱搞)
    暑假考试题4:星际旅行(欧拉路)
    暑假考试题3:jigsaw 黄金拼图(乱搞)
    暑假考试题3:baritone 上低音号与星星(链表+矩形统计)
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6139084.html
Copyright © 2011-2022 走看看