首页 > 解决方案 > 为什么insertBeg没有在开头插入节点

问题描述

我正在尝试insertBeg在开始时使用插入节点,但我无法正确

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

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

int length(struct node *n);
struct node *searchVal(struct node *n, int val);
struct node *createLinkedList(int data);
struct node *insertEnd(struct node *n, int data);
struct node *insertBeg( struct node *n, int data);
void printList(struct node *n);

int main(int argc, char **argv) {
    init = createLinkedList(1);
    insertEnd(init, 6);
    insertBeg(init, 9);
    printList(init);
}

void printList(struct node *n) {
    if (n != NULL) {
        while (n->next != NULL) {
            n = n->next;
            printf("%d", n->data);
        }
    } else {
        printf("Empty List");
    }
}

/**
 *  returns length of node
 */
int length(struct node *n) {
    int count = 0;
    if (!n) {
        return 0;
    }

    struct node *ptr = n;
    while(ptr != NULL) {
        count = count + 1;
        ptr = ptr->next;
    }
    return count;
}

struct node *searchVal(struct node *n, int val) {
    struct node *pos;
    if (!n) {
        return NULL;
    }


    struct node *ptr = n;
    while (ptr != NULL) {
        if (val == ptr->data){
            pos = ptr;
            return pos;
        } else {
            ptr = ptr->next;
        }
    }
    return NULL;
}

struct node *createLinkedList(int data) {
    struct node *new_node;
    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL) return NULL;
    new_node->data = data;
    new_node->next = NULL;

    return new_node;
}

struct node *insertBeg(struct node *n, int data) {
    struct node *new_node;
    new_node = (struct node *)malloc(sizeof(struct node));
    if (new_node == NULL) {
        return NULL;
    }

    new_node->data = data;
    new_node->next = n;
    n = new_node;
    return n;
}

struct node *insertEnd(struct node *n, int data){
    struct node *new_node, *temp;
    new_node = (struct node *)malloc(sizeof(struct node));

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

    new_node->data = data;
    if (n == NULL) {
        new_node->next = NULL;
        temp = new_node;
    } else {
        temp = n;
        while (temp->next != NULL) {
            temp = temp->next;
            temp->next = temp;
        }
        temp->next = new_node;
        new_node->next = NULL;
    }
    return temp;
}

标签: clinked-list

解决方案


insertBeg 返回一个节点,它应该是列表的新标头,您必须接受该返回类型并将其设置为新标头,如下所示:

int main(int argc, char **argv) {
    struct node * newHeader;
    init = createLinkedList(1);
    insertEnd(init, 6);
    newHeader = insertBeg(init, 9);
    init = newHeader;
    printList(init);
}

您还需要按如下方式编辑打印功能,因为您错过了那里的几个节点:

void printList(struct node *n) {
    if (n != NULL) {
        while (n != NULL) {
            printf("%d", n->data);
            n = n->next;
        }
    } else {
        printf("Empty List");
    }
}

您可以在此处查看完整代码以供参考:https ://ideone.com/WX9TKF


推荐阅读