bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_2 / eduincs / pgrm_026.cpp

pgrm_026.cpp (1217B)


      1 /* WAP to implement a singly linked list with insertion at the beginning and end */
      2 
      3 #include <iostream>
      4 using namespace std;
      5 
      6 class Node {
      7 public:
      8     int info;
      9     Node *next;
     10 
     11     Node(int val) {
     12         info = val;
     13         next = NULL;
     14     }
     15 };
     16 
     17 class SinglyList {
     18 private:
     19     Node *head;
     20 
     21 public:
     22     SinglyList() {
     23         head = NULL;
     24     }
     25 
     26     void insertBegin(int val) {
     27         Node *ptr = new Node(val);
     28         ptr->next = head;
     29         head = ptr;
     30         cout << "Inserted " << val << " at the beggining";
     31     }
     32 
     33     void insertEnd(int val) {
     34         Node *ptr = new Node(val);
     35         if (head == NULL) {
     36             head = ptr;
     37         } else {
     38             Node *t = head;
     39             while (t->next != NULL) {
     40                 t = t->next;
     41             }
     42             t->next = ptr;
     43         }
     44         cout << endl << "Inserted " << val << " at the end";
     45     }
     46 
     47     void display() {
     48       Node *t = head; cout << endl << "The list: ";
     49       while(t != NULL) {
     50         cout << t -> info << " ";
     51         t = t -> next;
     52       }
     53     }
     54 };
     55 
     56 int main() {
     57   SinglyList obj;
     58   obj.insertBegin(10);
     59   obj.insertBegin(20);
     60   obj.display();
     61   obj.insertEnd(40);
     62   obj.insertEnd(50);
     63   obj.display();
     64   return 0;
     65 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror