CS 301-Assignment 1

CS 301-Assignment 1
CS 301-Assignment 1


Solution:


Note:
Write code in Dev C++ and submit a file in .cpp. Make sure the output should be same as the sample output.

#include <iostream>
using namespace std;

class Node {
private:
    int data;
    Node* nextNode;

public:
    void setData(int value) {
        data = value;
    }

    int getData() {
        return data;
    }

    void setNext(Node* next) {
        nextNode = next;
    }

    Node* getNext() {
        return nextNode;
    }
};

class List {
private:
    Node* head;
    Node* current;
    Node* lastCurrent;

public:
    List() {
        head = NULL;
        current = NULL;
        lastCurrent = NULL;
    }

    Node* getHead() {
        return head;
    }

    void add(int value) {
        Node* newNode = new Node();
        newNode->setData(value);
        newNode->setNext(NULL);

        if (head == NULL) {
            head = newNode;
            lastCurrent = newNode;
        } else {
            lastCurrent->setNext(newNode);
            lastCurrent = newNode;
        }
    }

    void moveNext() {
        if (current == NULL) {
            current = head;
        } else {
            current = current->getNext();
        }
    }

    friend void traverse(List list);
    friend List createNodes();
    friend List mergeLists(List oddList, List evenList);
};

void traverse(List list) {
    Node* current = list.getHead();
    while (current != NULL) {
        cout << "List Element: " << current->getData() << endl;
        current = current->getNext();
    }
    cout << endl;
}

List createNodes() {
    List list;
    int input;

    for (int i = 0; i < 9; ++i) {
        cout << "Enter a numeric character: ";
        cin >> input;
        list.add(input);
    }
    return list;
}

List mergeLists(List oddList, List evenList) {
    List mergedList;

    Node* oddCurrent = oddList.getHead();
    Node* evenCurrent = evenList.getHead();

    while (oddCurrent != NULL) {
        mergedList.add(oddCurrent->getData());
        oddCurrent = oddCurrent->getNext();
    }

    while (evenCurrent != NULL) {
        mergedList.add(evenCurrent->getData());
        evenCurrent = evenCurrent->getNext();
    }

    return mergedList;
}

int main() {
    List inputList = createNodes();

    List oddList;
    List evenList;

    Node* current = inputList.getHead();

    while (current != NULL) {
        int digit = current->getData();
        if (digit % 2 == 0) {
            evenList.add(digit);
        } else {
            oddList.add(digit);
        }
        current = current->getNext();
    }

    cout << "\nOdd List: " << endl;
    traverse(oddList);

    cout << "Even List: " << endl;
    traverse(evenList);

    List mergedList = mergeLists(oddList, evenList);

    cout << "Merged List: " << endl;
    traverse(mergedList);

    return 0;
}

THE END😊