Facebook
From Sweet Mockingbird, 3 Years ago, written in C++.
This paste is a reply to Untitled from Speedy Tapir - go back
Embed
Viewing differences between Untitled and Insert node at tail
#include 

using namespace std;

class SinglyLinkedListNode {
    public:
        int data;
        SinglyLinkedListNode *next;

        SinglyLinkedListNode(int node_data) {
            this->data = node_data;
            this->next = nullptr;
        }
};

class SinglyLinkedList {
    public:
        SinglyLinkedListNode *head;

        SinglyLinkedList() {
            this->head = nullptr;
        }

};

void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) {
    while (node) {
        fout << node->data;

        node = node->next;

        if (node) {
            fout << sep;
        }
    }
}

void free_singly_linked_list(SinglyLinkedListNode* node) {
    while (node) {
        SinglyLinkedListNode* temp = node;
        node = node->next;

        free(temp);
    }
}

// Complete the insertNodeAtTail function below.

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

           
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    SinglyLinkedList* llist = new SinglyLinkedList();

    int llist_count;
    cin >> llist_count;
    cin.ignore(numeric_limits::max(), 'n');

  
    for (int i = 0; i < llist_count; i++) {
        int llist_item;
        cin >> llist_item;
        cin.ignore(numeric_limits::max(), 'n');

            SinglyLinkedListNode* llist_head = insertNodeAtTail(llist->head, llist_item);
              llist->head = llist_head;
    }


    print_singly_linked_list(llist->head, "n", fout);
    fout << "n";

    free_singly_linked_list(llist->head);

    fout.close();

    return 0;
}