Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

linked list help needed

Status
Not open for further replies.

john2020

Full Member level 5
Joined
Nov 13, 2005
Messages
292
Helped
12
Reputation
24
Reaction score
8
Trophy points
1,298
Activity points
4,911
I need to allocate a block of 256 bytes and insert into the first node linked list and free block from linked list.
 

I need to allocate a block of 256 bytes and insert into the first node linked list and free block from linked list.
what language are you using?
if C++ you have a number of container classes including <list>
 

I use c language. I am not aware of container classes. here is what i wrote so far...can u help me?

//insert a node into a linked list
struct node *pNew;
pNew = (struct node *) malloc(sizeof(struct node));
pNew -> data = item;
if (pPre == NULL){
//add before first logical node or to an empty list
pNew -> next = pHead;
pHead = pNew;
}
else {
//add in the middle or at the end
pNew -> next = pPre -> next;
pPre -> next = pNew;
}
 

please review this code and tell me if approach is correct? I am still not clear as to how to create new block of same size and add to exisitng list.also do i need to add node at the tail of the block?

#include <stdio.h> /* for printf */

#include <stdlib.h> /* for malloc */



struct node

{

int data;

struct node *next; /* pointer to next element in list */

};



struct node *list_add(struct node **p, int i)

{

struct node *n = malloc(sizeof(struct node));

if (n == NULL)

return NULL;



n->next = *p; /* the previous element (*p) now becomes the "next" element */

*p = n; /* add new empty element to the front (head) of the list */

n->data = i;



return *p;

}



void list_remove(struct node **p) /* remove head */

{

if (*p != NULL)

{

struct node *n = *p;

*p = (*p)->next;

free(n);

}

}

int main(void)

{

struct node *n = NULL;



list_add(&n, 0); /* list: 0 */

list_add(&n, 1); /* list: 1 0 */


return 0;

}





 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top