Guys, please help me with these operations on linked list will ya? Please..
a. initializeList – to initialize the count to 0 and head to null.
b. deleteList – to delete any nodes in the linked list.
c. listEmpty – check if the linked list is empty.
d. printList – to print each number in the linked list.
this is my header file.
Code:
#ifndef LINKEDLISTH
#define LINKEDLISTH
typedef int ListEntry;
typedef struct listnode {
ListEntry entry;
struct listnode *nextnode;
} ListNode;
typedef int Position;
typedef struct list {
int count;
ListNode *head;
} List;
ListNode *makeListNode(ListEntry x);
void setPosition(Position p, List *L, ListNode **current);
void insertList(Position p, ListEntry x, List *L);
void Error(const char *ErrorDesc);
void initializeList(List *ptr);
void deleteList();
void printList(ListNode *L);
#endif
this is my main file.
Code:
//This file contains all functions implementation in linkedlist.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkedlist.h"
int main(void)
{
List *pList;
ListNode *listnode;
ListEntry x;
Position p;
initializeList(&pList); //question 1 a
printf("Enter the number of nodes: ");
scanf("%d", &p);
printf("Enter values:");
scanf("%d", &x);
while (x!=-999)
{
insertList(p, x, &pList);
scanf("%d", &x);
}
printList(&listnode);
deleteList();
return 0;
}
//read data n put the data into a structure
ListNode *makeListNode(ListEntry x)
{
ListNode *newPtr = (ListNode*)malloc(sizeof(ListNode));
if (newPtr == NULL) {
Error("Out of memory");
}
else {
newPtr->entry = x;
newPtr->nextnode = NULL;
}
return newPtr;
}
void setPosition(Position p, List *L, ListNode **current)
{
int i;
ListNode *nodePtr = L->head;
*current = nodePtr;
if( p < 0 || p > L->count )
{
Error("Invalid position\n");
}
else
{
for ( i = 0; i < p; i++)
{
nodePtr = nodePtr->nextnode;
*current = nodePtr;
}
}
}
void insertList(Position p, ListEntry x, List *L)
{
ListNode *newNodePtr = makeListNode( x );
ListNode *prevPtr = NULL;
if ( p == 0 )
{
newNodePtr->nextnode = L->head;
L->head = newNodePtr;
}
else
{
setPosition( p-1,L,&prevPtr );
prevPtr->nextnode = newNodePtr;
}
L->count++;
}
void Error(const char *ErrorDesc)
{
printf("%s",ErrorDesc);
}
void initializeList(List *ptr)
{
ptr->count=0;
ptr->head=NULL;
}
void deleteList(List *pList)
{
int numDelete;
ListNode *pPre;
ListNode *pCur;
pCur=pList->head;
printf("Enter integer to be deleted : ");
scanf("%d", &numDelete);
while (pCur!=NULL)
{
if (pCur->entry==numDelete)
{
pPre->nextnode=pCur->nextnode;
free(pCur);
}
else
pCur=pCur->nextnode;
}
}
void printList(ListNode *L) {
while(L!=NULL) {
printf("%d\t", L->entry);
L = L->nextnode;
}
}
Please correct me if there is any mistake..