diff --git a/program/CPP/reversell b/program/CPP/reversell new file mode 100755 index 0000000..6966446 Binary files /dev/null and b/program/CPP/reversell differ diff --git a/program/CPP/reversell.cpp b/program/CPP/reversell.cpp new file mode 100644 index 0000000..fb15c58 --- /dev/null +++ b/program/CPP/reversell.cpp @@ -0,0 +1,74 @@ +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; + Node(int data) + { + this->data = data; + next = NULL; + } +}; + +struct LinkedList { + Node* head; + LinkedList() { head = NULL; } + + /* Function to reverse the linked list */ + void reverse() + { + // Initialize current, previous and next pointers + Node* current = head; + Node *prev = NULL, *next = NULL; + + while (current != NULL) { + // Store next + next = current->next; + // Reverse current node's pointer + current->next = prev; + // Move pointers one position ahead. + prev = current; + current = next; + } + head = prev; + } + + /* Function to print linked list */ + void print() + { + struct Node* temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + } + + void push(int data) + { + Node* temp = new Node(data); + temp->next = head; + head = temp; + } +}; + +/* Driver code*/ +int main() +{ + /* Start with the empty list */ + LinkedList ll; + ll.push(20); + ll.push(4); + ll.push(15); + ll.push(85); + + cout << "Given linked list\n"; + ll.print(); + + ll.reverse(); + + cout << "\nReversed linked list \n"; + ll.print(); + return 0; +} \ No newline at end of file