C中的链表实施

New*_*bie 0 c linked-list

我是Linked LIsts的新手,我正在尝试在C中实现链接列表.在我的代码下面: -

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

struct node {
    int data;
    struct node *next;
};
void insert (struct node *head, int data);
void  print  (struct node *head);
int main()
{
    struct node *head ;
    head= NULL;
    printf("new\n");
    insert(head,5);
    printf("%d\n",head);
    insert(head,4);
    insert(head,6);
    print(head);
    print(head);
    print(head);


} 
void  insert(struct node *head,int data){

    printf("%d\n",head);
    if(head == NULL){
        head =malloc(sizeof(struct node));
        head->next = NULL;
        head->data = data;

    }
    else {
        printf("entered else\n");
        struct node *tmp = head;
        if(tmp->next!=NULL){
            tmp = tmp->next;
        }
        tmp->next  = malloc(sizeof(struct node));
        tmp->next->next = NULL;
        tmp->next->data = data;

    }

}


void print (struct node *head) {
    printf("%d\n",head);
    struct node *tmp = head;
    if (head == NULL) {
        printf("entered null\n");
        return;
    }
    while (tmp != NULL) {
        if (tmp->next == NULL) {
            printf("%0d", tmp->data);
        } else {
            printf("%0d -> ", tmp->data);
        }
        tmp = tmp->next;
    }
    printf("\n");
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时输出为: -

new
0
0
0
0
0
entered null
0
entered null
0
entered null
Run Code Online (Sandbox Code Playgroud)

头始终为null,并且不会更新null.它不会进入insert中的else循环.任何人都可以帮我解决这个问题.指出我正在做的错误.谢谢

jua*_*nza 6

您的代码中可能存在其他错误,但一个大问题是您正在尝试设置头节点insert,但这仅影响传入指针的本地副本,因此它在调用方没有任何影响:

void  insert(struct node *head,int data){
  ....
  head = malloc(sizeof(struct node)); // head is local, caller won't see this
Run Code Online (Sandbox Code Playgroud)

您还需要确保在传递非节点时,NULL实际上将新节点附加到头部.您可以通过将指针传递给指针或通过返回设置指针来解决第一个问题.例如,

void insert(struct node **head, int data) {
  if(*head == NULL) {
    // create the head node
    ...
    *head = malloc(sizeof(struct node)); 
    ....
  else {
    // create a new node and attach it to the head
    struct node* tmp = malloc(sizeof(struct node));
    ....
    (*head)->next = tmp;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,在main,你需要传递一个指向头指针的指针,即使用address-of运算符&:

struct node *head = NULL;
insert(&head, 5);
Run Code Online (Sandbox Code Playgroud)

注意问题的一部分是该功能试图做太多.它被调用insert,但如果传入的指针是,它会尝试创建一个新节点NULL.将这些责任分开会更好:

// allocate a node and set its data field
struct node* create_node(int  data)
{
  struct node* n = malloc(sizeof(struct node));
  n->next = NULL;
  n->data = data;
  return n;
}

// create a node and add to end node.
// return the new end node.
// end has to point to a valid node object.
struct node* append_node(struct node* tail, int node_data)
{
  struct node* new_tail = create_node(node_data);
  tail->next = new_tail;
  return new_tail;
}
Run Code Online (Sandbox Code Playgroud)