c - C 中带头节点的链表

标签 c linked-list queue

The type definition of the list is in linkedList.h as usual.

 #ifndef LINKEDLIST_H
 #define LINKEDLIST_H

 typedef struct snode {
        int value;  
        struct snode *next; 
 } snodeType;

 typedef struct hnode {int count;
        snodeType *first;
        snodeType *last; 
 } sList;

 sList* create_sList(void);
 int insert_element_s(sList *L, snodeType *p, int value);
 int delete_element_s(sList *L, snodeType *p); 
 sList* merge_lists(sList *L1, sList *L2);

 #endif /* LINKEDLIST_H */

问题是:

sList * create_sList(void) creates the list and returns it to the caller. It has to allocate memory for the header node, initialize the fields in the struct hnode.

sList* create_sList(void) {

    sList *list = NULL;
    list->first  = (sList*)malloc(sizeof(snodeType));
    list->last  = (sList*)malloc(sizeof(snodeType));

/*  2nd option
    sList *list = NULL;
    node = malloc(sizeof(snodeType));
    node->next= NULL;
    list->first = node;
    list->last = node;
*/

    return list;
}

我只需要启动这个链表,有人知道怎么做吗?

最佳答案

那应该只是:

sList * create_sList(void)
{
  sList *list = malloc(sizof *list);
  if(list != NULL)
  {
    list->count = 0;
    list->first = list->last = NULL;
  }
  return list;
}

这将返回一个没有元素的列表头,即一个空列表头。

关于c - C 中带头节点的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39615012/

相关文章:

python - tensorflow 队列操作中线程的目的是什么?

c - 如何使用 getchar_unlocked(),我没有得到以下代码中的流程?

c - 如何将数字插入到 C 中的二叉搜索树中?

c - 在c中查找指向链表中元素的指针

c - 使用队列进行图 BFS 遍历 [C]

elasticsearch - 如何检查 threadpool.XXX.queue_size 中定义的 ealastisearch 队列的当前大小?

c++ - 枚举和定义语句之间的区别

objective-c - 为什么 clang 优化会破坏我的内联汇编代码?

c - 如何在 C 中操作一般输出(不是数字或变量)?

C++如何在不丢失内存的情况下删除节点?