创建链表来实现队列

标签 c linked-list

我是 C 新手,我正在尝试编写一个链表,其中每个节点仅包含一个 int。结构体的定义是可以的,但是我还想编写方法来更新这个链表(在尾部添加元素并删除头元素)。 (我希望能够读取最近添加的元素)

我写了下面的函数,但是我不知道free应该在哪里发生以及如何实现。有人能帮我解决这个问题吗?

typedef struct Node{
    Node next = NULL;
    int number;
} Node;

void add_node(Node *LL,int val){ 
    // add node to the end of the linked list
    new_node = (struct Node *)malloc(1*sizeof(struct Node));
    new_node->number = val;
    Node n = *LL;
    while (n.next != NULL){
        n = n.next;
    }
    n.next = new_node;
}

void delete_head(Node *LL){
     // update the head
    *LL = LL->next;
    //free?
}

void update_LL(*LL,int val){
    add_node(*LL,val);
    delete_head(*LL);
}

最佳答案

我这样重命名你的数据结构:

struct pointer
            {
            int field; 

            struct pointer *link; 
            };
typedef struct pointer cell;  

然后我们就可以根据您的需要使用这个功能:

void ad_an_element_at_the_end_of_the_list()
         {
         cell *p=NULL;
         cell *ptr=head;

         int value;

         cout<<" Integer number to insert at the end of the list: ";
         cin>>value;
         p=(cell*)malloc(sizeof(cell));
         p->field=value;
         p->link=NULL;
         if(ptr==NULL) 
            {
            ptr=p;
            head=ptr;

            }else
                {
                if(ptr->link==NULL)  t
                  {
                  ptr->link=p;
                  head=ptr;

                  }else
                     {
                      while(ptr->link!=NULL) 
                        {
                        ptr=ptr->link;
                        }
                     ptr->link=p;

                    }
            }
    }

关于创建链表来实现队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26240172/

相关文章:

python - DoubleLinkedList 获取内存位置而不是节点值 - Python

c - 如何正确识别我的构建平台?

c - 在 C 中生成数独板

c - 在 C 函数中获取 char 指针并向其添加字符

c - 对字符串链表进行排序时出现运行时错误

c - C 中的数组到列表(迭代)

c - Gtk 文件管理器作为顶部窗口打开

用于更新 UI 的 C GTK+ 周期性事件

c++ - 无法在赋值中将 'listNode**' 转换为 'listNode*'

algorithm - 100万节点的链表如何实现?