value) 就可以获得最后一个元素的值40、而不是遍历每一个元素? #include #include-6ren">
gpt4 book ai didi

c - 遍历链表获取值有什么意义,直接就可以得到吧?

转载 作者:行者123 更新时间:2023-11-30 21:43:11 24 4
gpt4 key购买 nike

为什么我们甚至需要遍历列表,尽管如果我按照行中的方式执行 printf("%d", end->value) 就可以获得最后一个元素的值40、而不是遍历每一个元素?

#include <stdio.h>
#include <stdlib.h>

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

void print(struct node *top) {
while (top != NULL) {
printf("%d\n", top->value);
top = top->next;
}
}

int main(void) {
struct node *head;
struct node *second;
struct node *end;

head = NULL;
second = NULL;
end = NULL;

head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
end = (struct node*)malloc(sizeof(struct node));

head->value = 5;
head->next = second;

second->value = 9;
second->next = end;

end->value = 10;
end->next = NULL;

printf("%d\n", end->value ); /*I m directly getting the output as 10,
whats the use of traversing through the list to get the same value? */

print(head); /*this is the use of the function to traverse through the
list*/
}

最佳答案

在您的情况下,直接获取值没有任何缺点,但在许多其他情况下,您将使用一些函数来创建新节点,并且通常您只有一个直接指向节点的指针(通常是头部)。所以这里直接抓取值并没有错,但大多数情况下并没有抓取值的选项,如果想获取值就需要遍历

关于c - 遍历链表获取值有什么意义,直接就可以得到吧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55540334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com