【问题标题】:Correctly Implementing a Linked List in C在 C 中正确实现链表
【发布时间】:2018-07-29 19:03:14
【问题描述】:

我正在尝试在 C 中从头开始实现一个链表:

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

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

void insert(struct node** root, int data){ 

    // Create a Node

    struct node * temp = malloc(sizeof(struct node));
    temp->data = data;
    temp->next = NULL;

    // Either root is NULL or not

    if (*root == NULL){
        *root = temp; // Directly modify the root
    }

    else {
        struct node * t = *root;
        while (t->next!=NULL){
            t = t->next;
        }
        t->next = temp; // Append at the last
    }
}

void printList(struct node * root){

    while(root!=NULL){
        printf("%d\t", root->data);
    }

}

struct node * search(struct node* root, int key){

    while (root!=NULL) {
        if (root->data == key) return root;
    }

    return NULL;
}

int main(){

    struct node * head = NULL;

    insert(&head,0);
    insert(&head,1);
    insert(&head,2);
    insert(&head,3);
    insert(&head,4);

    printList(head);

}

现在,当我运行程序时,我的输出是:

0       0       0       0       0       0       0       0       0       0

但是,我的列表不包含全零或 10 个元素。

我的逻辑似乎是正确的,但不知何故代码有一个错误。

顺便说一句,有没有办法避免双指针,我不能在插入链表时只使用指针吗?

【问题讨论】:

  • [c++] 语言与这个问题有什么关系?
  • @user2079303链表在c plus中实现类似
  • while(root!=NULL){ root 在这个打印循环中永远不会改变。顺便说一句:这是更喜欢 for() 循环而不是 while() 循环的一个很好的理由。
  • My logic is correct but somehow code has a bug. 这不是它的工作原理。乍一看,您的 printList 函数不会遍历列表,而只会打印 root->data。
  • @mourinho 在 C 中避免双指针的唯一方法是 insert 返回头指针,例如:struct node *insert(struct node* root, int data) ...

标签: c algorithm data-structures linked-list


【解决方案1】:

printList() 函数中有一个小错误。

printList() 函数中,root 未更新,要迭代整个列表,您应该执行root = root-&gt;next

void printList(struct node * root){

        while(root!=NULL){
                printf("%d\t", root->data);
                root = root->next; /* you miss this one */
        }

}

search() 函数中也出现同样的错误,

struct node * search(struct node* root, int key){
        while (root!=NULL) {
                if (root->data == key)
                        return root;
                else
                        root = root->next; /* if key not found root should be updated to next one */
        }
        return NULL;
}

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2018-10-16
    • 2015-08-31
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多