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 */