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;
    }

    运行结果如下:

  • 相关阅读:
    表单的编辑添加和删除 .removeClass() .append() .preAll() .attr('b') document.createElement()
    菜单与内容下拉jQuery
    s2选择框的全选和反选jQuery
    作用域
    当前触发事件的两种方式(onclick) 和 ('id') 获取
    词义分析
    Qt下载地址
    字符集(编码)转换_Qt532_QString
    字符集(编码)转换_Windows
    字符集(编码)转换_Linux
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6139084.html
Copyright © 2011-2022 走看看