【问题标题】:Creating a linked list WITHOUT a global head?创建一个没有全局头的链表?
【发布时间】:2015-02-26 02:14:41
【问题描述】:

对于处理递归的赋值,我们应该读入文件的值,并将变量存储到链表中。这里唯一的问题是,对于这个特定的任务,我们不能有一个全局负责人。教授。在课堂上向我们展示了如何在本地创建链表的头部。只是,我没有时间写下来。现在,为了抢占任务的先机,我被卡住了,因为我无法在链表中存储或遍历它,因为我不知道如何使用全局头。 p>

我通常这样建立结构和头部:

struct node
{
     int head;
     struct node *next;
}*head;

但我终其一生都无法弄清楚如何在没有头脑的情况下做到这一点。

我知道这可能与双指针有关

  **head

【问题讨论】:

  • 指向链表第一个元素的指针必须存在于某处,但绝不要求它作为全局存在。只需将它作为参数传递给需要它的函数即可。
  • 这个答案很有帮助:stackoverflow.com/a/19193703/156811
  • 我怎样才能指向没有全局头的第一个节点?

标签: c linked-list global head


【解决方案1】:
there needs to be a 'first' pointer for the linked list.

As I understand your problem, only a global head pointer is dis-allowed. 

so put the head pointer on the stack in the main() function 
and pass the address of that pointer (not the pointer contents) 
to each of the functions that need access to it.

【讨论】:

    【解决方案2】:

    “双指针”,“非全局头指针”。您使用本地指针作为头部,使用双指针作为追加,示例代码:

    node * head;
    node **ppnode = &head;       // pointer to head or to .next
    node * pnode;
    // ...
        pnode = new ...
        pnode-> ... 
        pnode->next = 0;
        *ppnode = pnode;         // set head or a next pointer
        ppnode = &(pnode->next); // advance ppnode
    

    【讨论】:

      【解决方案3】:

      节点定义为:

      struct node
      {
          int data;
          struct node *next;
      };
      

      无论如何,在同一个声明中声明变量和类型都是不好的风格。然后在main()有:

      struct node *head=NULL;
      

      照你原样继续。

      【讨论】:

        【解决方案4】:

        这是没有全局头的示例链表。

        #include <stdio.h>
        #include <stdlib.h>
        
        struct node {
            int data;
            struct node *next;
        };
        
        void insert(struct node **head, int val) {
            struct node *new = (struct node *)malloc(sizeof(struct node));
            new->data = val;
            if(*head)
                new->next = *head;
            *head = new;
        
        }
        
        void print_list(struct node *list) {
            while(list) {
                printf("%d\n", list->data);
                list = list->next;
            }
        }
        
        int main(void)
        {
            struct node *head = NULL;
        
            insert(&head, 1);
            insert(&head, 2);
            insert(&head, 3);
            print_list(head);
        
        return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多