如何使用链接列表正确实现队列

时间:2015-02-20 21:14:58

标签: c pointers linked-list queue

我目前正在做作业。在我的程序中,我不得不使用队列,所以我用链接列表编写了一个队列。但它似乎不喜欢我的语法。

所以我有结构

  typedef struct Node{
  pthread_t thread;
  int threadID;
  int securityMode;  // nTS = 1, S = 2, U = 3
  //int cluseterHalf;  //either 1st or 2nd
  struct NODE *next;
  int executionTime;
  int isLast;
}NODE;
typedef NODE *Link;

这就是我尝试排队的地方。

void Enqueue(Link node, Link *Queue){
  Link previous = NULL;
  Link current = *Queue;
  while (current->isLast){
    previous = current;
    current = current->next;
  }
  if(previous == NULL){
    node->next = current;
    *Queue = node;
  }
  else{
    previous->next = node;
    node->next = current;
  }
}

我尝试更改我的代码,但是我收到了这个错误。

Cluster.c:162:13: warning: assignment from incompatible pointer type
[enabled by default]
     current = current->next;
             ^
Cluster.c:165:16: warning: assignment from incompatible pointer type [enabled by default]
     node->next = current;
                ^
Cluster.c:169:20: warning: assignment from incompatible pointer type [enabled by default]
     previous->next = node;
                    ^
Cluster.c:170:16: warning: assignment from incompatible pointer type [enabled by default]
     node->next = current;

我试着看一些类似于我的stackoverflow问题。 1)Question1

所以我做了许多逻辑和非逻辑尝试。我试着写 node-> next =& current,因为next是一个指针,它将获得地址值。但它不起作用:( 我也尝试过oposit *(node-> next)= current

我终于为我找到了正确的选择,但我不确定这是否是我想要的。我以为我必须接下来才有结构NODE * 但如果我在NODE旁边更改NODE *,那么我就不会收到这些错误。但我得到了不同的一个:

Cluster.c:25:15: error: field ‘next’ has incomplete type
   struct NODE next;

你能告诉我如何解决这个问题吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

尝试在定义结构时将struct NODE *next;更改为struct Node *next;

修改

查看代码,我认为你在指针赋值时遇到了一些问题。例如,我认为Link current = *Queue;只会分配Queue的数据,而不会分配地址,因此您无法访问"内部"。同样的问题可能与之前有关。

另外,我真的不明白Link的目的是什么,你可以只用NODE

答案 1 :(得分:1)

发布的代码在维护时会出现很多问题。此外,代码包含几个混乱的区域,使理解/调试变得不必要。有意义的变量名称也有很大帮助。建议:

struct Node
{
    pthread_t thread;
    int threadID;
    int securityMode;  // nTS = 1, S = 2, U = 3
    //int cluseterHalf;  //either 1st or 2nd
    struct Node *next;
    int executionTime;
    // notice removal of unneeded field isLast
};


void Enqueue(struct Node *newNode, struct Node **Queue)
{
    struct Node *current = *Queue;

    newNode->next = NULL;

    if(NULL == current)
    { // then handle special case of empty linked list
        *Queue = newNode;
    }

    else
    { // else, some nodes already in linked list
        // loop to end of linked list
        while (NULL != current->next)
        {
            // step to next node in linked list
            current = current->next;
        } // end while

        // add node to end of linked list
        current->next = newNode;
    } // end if
} // end function: Enqueue