【问题标题】:Print cricular single linked list recursively in C在C中递归打印循环单链表
【发布时间】:2020-04-07 16:51:39
【问题描述】:

我应该在 C 中的循环单链表上递归地工作,我的问题是,由于是递归的,我无法正确打印列表,并且在访问 display() 中的 tmp-> 键时遇到了一些问题当我推送超过 1 个元素并且我想稍后显示列表时的功能(由于非法访问导致的分段错误)。 tmp 和 list 都声明为 struct node* tmp = NULL;struct node* list = NULL; 主要摘录:

    case 8:
tmp = list;
        if (tmp->next == tmp)
    printf("\n%d\n", tmp->key);
else
            display (list, tmp);
        break;

功能:

void display (struct node* head, struct node* tmp){

    if (head != NULL){
        if (tmp != head){
            printf ("%d ", tmp->key);
            tmp = tmp->next;
            display(head, tmp);
        }
    }
}

【问题讨论】:

  • 您只管理具有 一个 单元格的循环列表?
  • @bruno 你是什么意思?如果您的意思是一个字段(键),那么是的,它只需要一个字段。
  • 不,我问是因为我只看到 list->next == list / tmp->next == tmp 的情况,所以具有一个单元格的循环列表,您不会检测到两个单元格的循环列表,其中 list->next != listlist->next->next == list

标签: c linked-list circular-list


【解决方案1】:

该设计建议tmp 应指向列表中的现有节点。

如果tmpNULL,您必须在display() 中检查该条件以避免分段错误。

您还需要检查 tmp 在此代码之前是否为 NULL

        if (tmp->next == tmp)

【讨论】:

  • 我不需要检查 tmp 是否为 NULL,因为我在调用 display 之前将列表的头部分配给了 tmp,请问我应该在哪里编辑我的代码?因为我真的不明白
  • 请提交尽可能多的代码以允许其他 SO 用户编译测试。您在上面提到'我在调用 display 之前将列表的头部分配给 tmp',但你的问题只说'struct node* tmp = NULL'和'struct node* list = NULL'。这意味着 tmp 和 list 都是 NULL。你提供的细节越详细,我或其他人就越有能力回答。
【解决方案2】:
void display (struct node *head, struct node *this){

    if (!head) return;
    if (!this) return;

    printf ("%d ", this->key);

    if (this->next == head) return;
    display(head, this->next);
}

并且,编译器删除了尾递归(gcc -O4 -S):


.globl  display
        .type   display, @function
display:
.LFB24:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rdi, %rbp
        pushq   %rbx
        .cfi_def_cfa_offset 24
        .cfi_offset 3, -24
        subq    $8, %rsp
        .cfi_def_cfa_offset 32
        testq   %rdi, %rdi
        je      .L1
        testq   %rsi, %rsi
        movq    %rsi, %rbx
        jne     .L4
        jmp     .L1
        .p2align 4,,10
        .p2align 3
.L12:
        testq   %rbx, %rbx
        je      .L1
.L4:
        movl    8(%rbx), %edx
        xorl    %eax, %eax
        movl    $.LC0, %esi
        movl    $1, %edi
        call    __printf_chk
        movq    (%rbx), %rbx
        cmpq    %rbp, %rbx
        jne     .L12
.L1:
        addq    $8, %rsp
        .cfi_def_cfa_offset 24
        popq    %rbx
        .cfi_def_cfa_offset 16
        popq    %rbp
        .cfi_def_cfa_offset 8
        ret
        .cfi_endproc
.LFE24:
        .size   display, .-display

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    相关资源
    最近更新 更多