答疑解惑必采纳 2021-08-04 20:49 采纳率: 91.3%
浏览 16
已结题

C语言,查找链表的长度,补全一下我的这个代码

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

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

int length(struct node *head);
struct node *strings_to_list(int len, char *strings[]);

// DO NOT CHANGE THIS MAIN FUNCTION

int main(int argc, char *argv[]) {
// create linked list from command line arguments
struct node *head = strings_to_list(argc - 1, &argv[1]);

int result = length(head);
printf("%d\n", result);

return 0;

}

// Return the length of the linked list pointed by head
int length(struct node *head) {

// PUT YOUR CODE HERE (change the next line!)
return 42;

}

// DO NOT CHANGE THIS FUNCTION

// create linked list from array of strings
struct node *strings_to_list(int len, char *strings[]) {
struct node *head = NULL;
for (int i = len - 1; i >= 0; i = i - 1) {
struct node *n = malloc(sizeof (struct node));
assert(n != NULL);
n->next = head;
n->data = atoi(strings[i]);
head = n;
}
return head;
}

  • 写回答

1条回答 默认 最新

  • CSDN专家-link 2021-08-04 20:52
    关注
    int length(struct node *head) {
      struct node *p = head;
      int count  = 0;
    while(p != NULL)
    {
        count++;
        p = p->next;
    }
      return count;
    
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月12日
  • 已采纳回答 8月4日
  • 创建了问题 8月4日

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据