воскресенье, 28 октября 2018 г.

Insert a Node at the Head of a Linked List



SinglyLinkedListNode* insertNodeAtHead(SinglyLinkedListNode* llist, int data) {
    if (llist == nullptr)
    {
        llist = new SinglyLinkedListNode(data);
    }
    else
    {
        SinglyLinkedListNode* firstNode = new SinglyLinkedListNode(data);
        firstNode->next = llist;
        llist = firstNode;
    }
    return llist;
}


среда, 24 октября 2018 г.

Day 4: Class vs. Instance







#include <iostream>
using namespace std;

class Person {
public:
    int age;
    Person(int initialAge);
    void amIOld();
    void yearPasses();
};

Person::Person(int initialAge) {
    // Add some more code to run some checks on initialAge
    if (initialAge < 0) {
        age = 0;
        cout << "Age is not valid, setting age to 0.\n";
    }
    else {
        age = initialAge;
    }
}

void Person::amIOld() {
    // Do some computations in here and print out the correct statement to the console
    if (age < 13) {
        cout << "You are young.\n";
    }
    else if (age >= 13 && age < 18) {
        cout << "You are a teenager.\n";
    }
    else {
        cout << "You are old.\n";
    }
}

void Person::yearPasses() {
    // Increment the age of the person in here
    age++;
}


int main() {
    int t;
    int age;
    cin >> t;
    for (int i = 0; i < t; i++) {
        cin >> age;
        Person p(age);
        p.amIOld();
        for (int j = 0; j < 3; j++) {
            p.yearPasses();
        }
        p.amIOld();

        cout << '\n';
    }

    return 0;
}

Insert a Node at the Tail of a Linked List









Print the Elements of a Linked List

void printLinkedList(SinglyLinkedListNode* head) {
    while (head)
    {
        cout << head->data << endl;
        head = head->next;
    }
}

Insert a Node at the Tail of a Linked List

 
// Complete the insertNodeAtTail function below.

/*
 * For your reference:
 *
 * SinglyLinkedListNode {
 *     int data;
 *     SinglyLinkedListNode* next;
 * };
 *
 */
SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
    if (head == nullptr)
    {
        head = new SinglyLinkedListNode(data);
    }
    else
    {
        SinglyLinkedListNode* current = head;
        while (current->next != nullptr)
        {
            current = current->next;
        }
        current->next = new SinglyLinkedListNode(data);
    }
    return head;
}


The Love-Letter Mystery

/* Джеймс раздобыл любовное письмо, которое его друг Гарри написал своей девушке. Будучи шутником, Джеймс решил изменить его. Он ...