C 链表的实现

im3dabasia

我正在尝试打印存储在链接列表中的值,但我遇到了一个无限循环。请有人告诉我我的代码有什么问题。我能够成功收集节点的数据,但是在打印列表时我遇到了连续循环。任何帮助将不胜感激。提前致谢

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

struct node {
    int data; //4 bytes
    struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
};

int main(){
    struct node *head,*newnode,*temp;
    head = NULL ;
    temp = head;
    int count=0, choice=1;

    while(choice){
        newnode = (struct node *)malloc(sizeof(struct node));
        printf("Enter data:");
        scanf("%d",&newnode-> data);
        newnode->next = head;

        if(head == 0){
            head = temp = newnode;
        }
        else{
            temp->next = newnode;
            temp = newnode;

        }
        printf(" %d ",temp->data);

        printf("Do you want to continue? 0/1");
        scanf("%d",&choice);
    }
    int i = 0;
    temp = head;
    while( temp!=NULL){
        printf("%d ",temp->data);
        temp=temp->next;
    }
}
克里斯

我怀疑它是否在所讨论的作业问题的范围内,但是将链表任务分解为更小的问题确实很有帮助。

我们从这个节点定义开始:

struct node {
    int data; //4 bytes
    struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
};

我将使用 typedef 使我的生活更轻松。

typedef struct node {
    int data; //4 bytes
    struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
} node_t;

让我们找到给定头部的最后一个节点。我们将创建一个node_t名为指针current并使用它来遍历列表,直到它到达最后一个节点。我们会知道它是最后一个,因为它的next成员将是NULL. 当然,如果headNULL,那么我们会NULL立即返回

node_t *last_node(node_t *head) {
    if (head == NULL) {
        return NULL;
    }

    node_t *current;

    for (current = head; current->next != NULL; current = current->next);

    return current;
}

现在,让我们向具有给定头部的列表添加一个值。我们可以通过返回一个指向新的最后一个节点的指针来提供快捷方式。如果head是 ,我们也会短路很多工作NULL

否则,我们将使用last_node我们定义函数获取最后一个节点,将其设置next为新节点,并返回一个指向新节点的指针。

node_t *add_to_list(node_t *head, int value) {
    node_t * new_node = malloc(sizeof(node_t));
    new_node->data = value;
    new_node->next = NULL;

    if (head == NULL) {
        return new_node;
    }

    node_t *last = last_node(head);
    last->next = new_node;
    return new_node;
}

最后我们可以编写一个函数来打印列表。鉴于您已经看到了遍历列表,这应该看起来很熟悉。

void print_list(node_t *head) {
    for (node_t *current = head; 
         current->next != NULL; 
         current = current->next) {
        printf("%d ", current->data);
    }
}

将大问题分解为小问题至关重要。练习吧!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章