Write a C++ program that would be able to manipulate a list of fruits. First, create a link
list that has this fruit list:

apple | banana | peach | apple | mango | durian | rambutan | kiwi

i. Then, sort the fruits in alphabetical order and display the sorted list

ii. Count the number of different fruits (repeated fruits are counted once only).

iii. Ask for a new fruit and:
a. If the fruit exists – print the word “Exists“ and insert after the repeated
fruit.
b. If the fruit does not exist – insert in the correct position (sorted list).

(40 mark)

First you take a stab at it, post your code, tell us what's giving you a problem.

But then you'd know that if you read the sticky posts at the top of this forum.

#include <stdio.h>

typedef char ELEMENT;
typedef struct node {
    ELEMENT data;
    struct node *next;
} NODE;

void CreateList (NODE **sList) {
    *sList = NULL;
}

NODE *NewNode(ELEMENT dataelement) {
    NODE *Nnode;
    Nnode = (NODE *) malloc (sizeof(NODE));
    if (Nnode != NULL) {
        Nnode->data = dataelement;
        Nnode->next = NULL;
    }
    return Nnode;
}

typedef enum bool {FALSE, TRUE} BOOL;
BOOL EmptyList (NODE *sList) {
    return ((BOOL) (sList == NULL));
}

void TraverseList (NODE *sList) {
    NODE *pnode;
    for (pnode = sList; pnode != NULL; pnode->next) {
        printf("pnode.data : %c -> \n", pnode->data);
    }
    printf("NULL");
}

BOOL SearchList (NODE *sList, ELEMENT dataelement, NODE **pnode) {
    NODE *qNODE;
    qNODE = sList;
    *pnode = NULL;
    while (qNODE != NULL) {
        if (qNODE->data == dataelement)
            return (BOOL) (TRUE);
        else {
            *pnode = qNODE;
            qNODE = qNODE->next;
        }
    }
    return (BOOL) (FALSE);
}


void InsertList(NODE **sen, NODE *temp, NODE *p) {
    if (p == NULL) {
        temp->next = *sen;
        *sen = temp;
    } else {
        temp->next = p->next;
        p->next = temp;
    }
}

void DeleteList (NODE **sList, NODE *pnode) {
    NODE *temp;
    if (EmptyList(*sList)) {
        printf("Deletion Error: Empty List");
        return;
    }
    if (pnode == NULL) {
        temp = *sList;
        *sList = temp->next;
    } else {
        temp = pnode->next;
        pnode->next = temp->next;
    }
    free(temp);
}

void main() {
    char item;
    NODE *list, *tempNode;
    CreateList(&list);

    printf("Enter word ending with '$' symbol: ");
    while ((item = getchar()) != '$') {
        tempNode = NewNode(item);
        InsertList(&list, tempNode, NULL);
    }
    TraverseList(list);
    printf("\n");
}

Edited 3 Years Ago by pritaeas: Fixed formatting

i got 2 error... i got headache.. huhuhuh.. donno how to do..

This article has been dead for over six months. Start a new discussion instead.