【问题标题】:Linked List multiple arrows in CC中的链表多个箭头
【发布时间】:2020-06-20 15:32:02
【问题描述】:

关于数据结构中链表的问题(C语言) 假设我在列表中有 4 个元素,就像
(地址)[数据 |指向下一个块的指针]

像这样 (252) [5 | 272]--> (272)[8 |286]--> (286)[11 | 296]--> (296)[15|NULL]

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

struct node* head; //global variable 

这是关于箭头控制的问题 如果我想从头部遍历到第4个元素,我可以这样说吗?

(252) [5 | 272]--> (272)[8 |286]--> (286)[11 | 296]--> (296)[15|NULL]---X

// let's suppose I stored 1st element in a variable and already linked them together 

struct node* temp1 = (struct node*) malloc(sizeof(struct node*));
temp1->data = 5;
temp1->next = 272;
.
.
.

我可以这么说吗

temp1->next; // value is 272
temp1->next->data; // data is 8

temp1->next->next; // value is 286
temp1->next->next->data; //data is 11

temp1->next->next->next; // value is 296
temp1->next->next->next->data; // value is 15

temp1->next->next->next->next; // value is NULL

是否可以使用多个箭头直接遍历链表而不是使用循环?

【问题讨论】:

标签: c linked-list


【解决方案1】:

您可以,但前提是您确定 所有 您想要的元素之前的元素具有有效的 next 指针,或者换句话说,只有当您确定列表包含足够的元素。

之所以通常在循环中完成,是因为您通常不知道列表的长度,并且您需要检查每个元素以确保。如果您不知道列表中有多少元素,那么直接执行->next->next->... 会导致程序取消引用NULL 指针,这是未定义的行为。

【讨论】:

    【解决方案2】:

    我认为你在犹豫是因为你得到了链条。为了防止这种长链接,我们使用while-loop,例如:

    int main()
    {
        struct node* head = (struct node*) malloc(sizeof(struct node))
        // you want to be saving space for a new struct on the heap
        // not space for a struct pointer on the heap
    
        // addNodeAtEnd(&head, 0);
        // addNodeAtEnd(&head, 1);
        // addNodeAtEnd(&head, 2);
        // ...
    
        if (head != NULL) {
            struct node* p = head;
            while (p->next != NULL) {
                p = p->next;
                ; // do something like printf(p->data)
            }
        }
    }
     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多