From 280e93349f994642a54aa9c400598ad0cd3cfa2b Mon Sep 17 00:00:00 2001 From: Ashutosh <66676728+Ashutosh-ops@users.noreply.github.com> Date: Wed, 7 Oct 2020 15:35:17 +0530 Subject: [PATCH] A super cpp program to operate singly link list This is a simple but super cpp program to operate singly link list. --- super_link_list.cc | 114 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 super_link_list.cc diff --git a/super_link_list.cc b/super_link_list.cc new file mode 100644 index 0000000..d731740 --- /dev/null +++ b/super_link_list.cc @@ -0,0 +1,114 @@ +#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; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +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); + } +} + +SinglyLinkedListNode* deleteNode(SinglyLinkedListNode* head, int index) { + + if(index ==0) + { + SinglyLinkedListNode* ptr = head; + head = head->next; + free(ptr); + return head; + } + + SinglyLinkedListNode* p = head; + for (int i = 0; i != index-1; i++) + { + p = p->next; + } + SinglyLinkedListNode* q; + q = p->next; + p->next = q->next; + free(q); + return head; +} + +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'); + + llist->insert_node(llist_item); + } + + int position; + cin >> position; + cin.ignore(numeric_limits::max(), '\n'); + + SinglyLinkedListNode* llist1 = deleteNode(llist->head, position); + + print_singly_linked_list(llist1, " ", fout); + fout << "\n"; + + free_singly_linked_list(llist1); + + fout.close(); + + return 0; +}