链表程序 [英] linked list program

查看:35
本文介绍了链表程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待下面的链表程序打印1但事实并非如此.有人能弄清楚为什么吗?

I am expecting the below linked list program to print 1 but its not.can anyone figure out why?

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

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

typedef struct node  NODE;
void display(NODE *);
void add(NODE *,int );

int main()
{
  NODE *head=NULL;
  add(head,1);
  display(head);
  printf("\n");
  getch();
  return 0;
}

void display(NODE *pt)
{
  while(pt!=NULL)
  {
    printf("element is");
    printf("%d",pt->data);
    pt=pt->link;
  }
}

void add(NODE *q,int num)
{
  NODE *temp;
  temp = q;
  if(q==NULL)
  {
    q=(NODE *)malloc(sizeof(struct node));
    temp = q;
  }
  else
  {
    while((temp=temp->link)!=NULL);
    temp->link = (NODE *)malloc(sizeof(struct node));
    temp=temp->link;
  }

  temp->data = num;
  temp->link  = NULL;
}

推荐答案

您的 add 方法在首次调用时(当 head == NULL 时)应添加第一个节点到列表,从而更改 head 指向新分配的节点.

Your add method when called first time (when head == NULL) should add the first node to the list thus changing head to point to the newly allocated node.

但这不会发生,因为 add 不会将更改后的 head 回传给调用者.

But this does not happen as add does not communicate back the changed head to the caller.

要解决此问题,您可以从函数中返回修改后的 head :

To fix this you can either return the modified head from the function:

// call as before but assign the return value to head.
head = add(head,1);

.....

// return type changed from void to NODE *
NODE* add(NODE *q,int num)
{
    // make the changes as before

    // return the head pointer.  
    return q;
}

或者您也可以按如下方式将指针 head 通过地址传递给函数 add :

or you can pass the pointer head by address to the function add as:

// pass the address of head.
add(&head,1);

.....

// change type of q from NODE * to NODE **
void add(NODE **q,int num)
{
  // same as before but change q to *q.

  // any changes made to the list here via q will be visible in caller.
}

这篇关于链表程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆