Re: Link lists..



johnnash wrote:
i'm declaring a data structure for link list of integers in A.h

#ifndef A_H (can anyone please explain how ifndef works as well..i
just seem to see it in almost every program)

#define A_H

typedef struct node nodestruct

{

int data;

struct node *next;

}node;

extern node * head /*indicates head node of the list , declaring as
extern so that it can be used in A.c */



Now i want to use this link list so..A.c


#include "A.h"

node * head; /*definition, is this sufficient for link list ?, can i
initialize head to NULL here itself */

LL()/* computes the link list */
{

node *p, *prev; /*prev is previous node */

head = NULL;

head->next = NULL;
Swap these 2 lines, otherwise you derefference a NULL pointer


for(i=0;i<10;i++) /*Creating list of 10 elements */

{

p = (node *) malloc(sizeof(node));
lose the cast. Instead #include <stdlib.h>

p->next = NULL;
check p first. malloc() can fail, if so you derefferent a NULL pointer here


scanf("%d",&(p->data));
Avoid scanf. At least consider what happens to the <return>

if(head ==NULL)

head = p;

else
{
prev->next = p;

prev = p;
}

}


main()

{

struct node *p;

LL();

p = head;

while(p!= NULL)
{
printf("%d\n",p->data);

p = p->next;

}

}


.



Relevant Pages

  • Re: Link lists..
    ... #ifndef A_H (can anyone please explain how ifndef works as well..i ... typedef struct node nodestruct ... extern node * head /*indicates head node of the list, ... warnings even if warning level is set at it's highest. ...
    (comp.lang.c)
  • LinkedList Pointer (REPOST - diff version)
    ... struct node * next; ... No problem until you are dealing with a pointer variable. ... void Push(struct node** headRef, int newData); ... Given an int and a reference to the head pointer (i.e. a struct ...
    (comp.lang.c)
  • LinkedList Pointer (REPOST - diff version)
    ... struct node * next; ... No problem until you are dealing with a pointer variable. ... void Push(struct node** headRef, int newData); ... Given an int and a reference to the head pointer (i.e. a struct ...
    (comp.lang.c)
  • Re: branch prediction optimization
    ... If you had a loop like ... head = NULL; ... although the first time through the loop will suffer. ... struct node *next; ...
    (comp.unix.programmer)
  • Re: linked lists
    ... >> why do you have a pointer to a pointer to a node p?? ... > Because I need to modify the original pointer 'head'. ... struct node *next; ... struct node *newnode; ...
    (comp.lang.c)