小编Joh*_*mac的帖子

虽然我们将常量放在大O符号中,但它在现实生活中是否重要?

虽然我知道大O符号只是简单地描述了算法的增长率,但我不确定以下O(n)算法之间在现实生活中的效率是否有任何差异.

从列表末尾打印链接列表中的节点值.

给定一个节点:

/* Link list node */
struct node
{
  int data;
  struct node* next;
};
Run Code Online (Sandbox Code Playgroud)

解决方案1 ​​O(n)

该解决方案迭代列表两次,一次找到列表的长度,而第二次去的列表的末尾- N的.

void printNthFromLast(struct node* head, int n)
{
    int len = 0, i;
    struct node *temp = head;


    // 1) Count the number of nodes in Linked List
    while (temp != NULL)
    {
        temp = temp->next;
        len++;
    }

    // Check if value of n is not more than length of the linked list
    if (len < …
Run Code Online (Sandbox Code Playgroud)

c c++ algorithm performance big-o

20
推荐指数
2
解决办法
1533
查看次数

标签 统计

algorithm ×1

big-o ×1

c ×1

c++ ×1

performance ×1