【问题标题】:C singly linked list head points to another node's headC单链表头指向另一个节点的头
【发布时间】:2021-11-19 00:30:53
【问题描述】:

我知道如何将节点的头部指向 int 值或 char 值;但是,我不知道如何将一个节点的头部指向另一个节点的头部。

例如, nodes head

节点“a”的下一个指向另一个(f)节点,其头指向“b”,其下一个指向节点“d”。我不知道如何让节点“f”的头指向节点“b”而下一个指向“d”。我写了这样的东西,但它不起作用。

a->data = 'a';
a->next = f;

f->data = b;
f->next = d;

b->data = 'b';
b->next = c;

【问题讨论】:

    标签: c linked-list singly-linked-list


    【解决方案1】:

    一个可能的解决方案:

    struct node {
      char char_data;
      struct node* node_data;
    
      struct node* next;
    };
    

    所以你有这些节点:

    struct node* a = ...;
    struct node* f = ...;
    struct node* b = ...;
    ...
    
    a->char_data = 'a';
    a->node_data = NULL;
    a->next = f;
    
    f->node_data = b;
    f->next = d;
    
    b->char_data = 'b';
    b->node_data = NULL;
    b->next = c;
    
    ...
    

    实际上,如果node->node_dataNULL,则意味着该节点包含char,因此您读取/设置它的node->char_data;如果node->node_data 不是NULL,则表示该节点指向另一个节点,因此忽略其node->char_data 成员,而是查看其node->node_data 成员。 p>

    【讨论】:

      【解决方案2】:

      考虑使用标记联合:

      struct node {
          enum { NODE_CHAR, NODE_INT, NODE_NODE } tag;
          union {
              char c;
              int i;
              struct node *node;
          };
          struct node *next;
      };
      

      现在你可以创建一个简单的树:

      // make a char node
      struct node node0 = { .tag = NODE_CHAR, .c = 'a' };
      // make it a predeccesor of `int` node
      struct node node1 = { .tag = NODE_INT, .i = 42, .next = &node0 };
      // make it a simbling of other char node
      struct node node2 = { .tag = NODE_CHAR, .c = 'b' };
      struct node node3 = { .tag = NODE_NODE, .node = &node2, .next = &node1 };
      

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多