函数returns链表中最旧的值

Function returns the oldest value in linked list

这是一个函数(last),returns链表中最旧的值(最后一个节点):

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

typedef struct node {
  int val;
  struct node *next;
}Elem, *Pointer;

Pointer init() { return NULL; }

void last(Pointer l)
{
  while (l != NULL)
  {
    l = l->next; 
  }
  printf("%d",l->val); 
}

int main(void) {
    Pointer myl =
    insert(3, insert(7, insert(5, 
    insert(11, insert(1, init ())))));

    last(myl);
}

所以函数 (last) 接受一个指向链表的指针,在 while 循环中它将指针移动到最后一个节点,然后打印它的值。

错误是: exited, segmentation fault.

因为检查 NULL l 是你退出循环的条件,当你到达循环结束时

while (l != NULL)
{
    l = l->next; 
}
printf("%d",l->val); 

l 为 NULL(否则你仍然会循环!)。因此,在下面的 printf 中,您正在取消引用 NULL 指针,这会导致 分段错误

您可以通过以下方式修改您的函数:

void last(Pointer l)
{
    if ( l != NULL )
    {
        while (l->next != NULL)
        {
            l = l->next; 
        }
        printf("%d",l->val); 
    }
}

只需查看元素的 next 字段,确保列表不为空(NULL 列表指针)。

  1. 切勿将指针隐藏在 typedef 后面。它使程序难以阅读且容易出错。
typedef struct node {
  int val;
  struct node *next;
}Elem;
  1. 这绝对是可怕的事情 - 避免
insert(3, insert(7, insert(5, 
insert(11, insert(1, init ())))));
  1. 函数。检查下一个值是否为 NULL。 IMO 更好的 return 指针,然后用它做点什么。还要始终检查参数是否有效。
Elem *last(Elem *first)
{
    if(first)
    {
        while(first -> next != NULL) 
        {
            first = -first -> next;
        }
    }
    return first;
}
  1. 打印出来
printf("%d\n", last(myl) -> val);