From 94f649795cef42d83c9c0c737b7c215bd8e56db2 Mon Sep 17 00:00:00 2001 From: ROhit123614 <53163601+ROhit123614@users.noreply.github.com> Date: Thu, 1 Oct 2020 23:01:28 +0530 Subject: [PATCH] Create convert a string to a singly linkedlist.cpp --- ...onvert a string to a singly linkedlist.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Queues, Stacks And LinkedList/convert a string to a singly linkedlist.cpp diff --git a/Queues, Stacks And LinkedList/convert a string to a singly linkedlist.cpp b/Queues, Stacks And LinkedList/convert a string to a singly linkedlist.cpp new file mode 100644 index 0000000..af67700 --- /dev/null +++ b/Queues, Stacks And LinkedList/convert a string to a singly linkedlist.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; + +// Structure for a Singly Linked List +struct node { + char data; + node* next; +}; + +// Function to add a new node to the Linked List +node* add(char data) +{ + node* newnode = new node; + newnode->data = data; + newnode->next = NULL; + return newnode; +} + +// Function to convert the string to Linked List. +node* string_to_SLL(string text, node* head) +{ + head = add(text[0]); + node* curr = head; + + // curr pointer points to the current node + // where the insertion should take place + for (int i = 1; i < text.size(); i++) { + curr->next = add(text[i]); + curr = curr->next; + } + return head; +} + +// Function to print the data present in all the nodes +void print(node* head) +{ + node* curr = head; + while (curr != NULL) { + cout << curr->data << " -> "; + curr = curr->next; + } +} + +// Driver code +int main() +{ + + string text = "GEEKS"; + + node* head = NULL; + head = string_to_SLL(text, head); + + print(head); + return 0; +}