答疑解惑必采纳 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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分