diff --git a/Middle of Linked List b/Middle of Linked List new file mode 100644 index 0000000..533f531 --- /dev/null +++ b/Middle of Linked List @@ -0,0 +1,70 @@ +#include +using namespace std; + +// Struct +struct Node +{ + int data; + struct Node* next; +}; + +/* Function to get the middle of the linked list*/ +void printMiddle(struct Node *head) +{ + struct Node *slow_ptr = head; + struct Node *fast_ptr = head; + + if (head!=NULL) + { + while (fast_ptr != NULL && fast_ptr->next != NULL) + { + fast_ptr = fast_ptr->next->next; + slow_ptr = slow_ptr->next; + } + printf("The middle element is [%d]\n\n", slow_ptr->data); + } +} + +// Function to add a new node +void push(struct Node** head_ref, int new_data) +{ + /* allocate node */ + struct Node* new_node = new Node; + + /* put in the data */ + new_node->data = new_data; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +// A utility function to print a given linked list +void printList(struct Node *ptr) +{ + while (ptr != NULL) + { + printf("%d->", ptr->data); + ptr = ptr->next; + } + printf("NULL\n"); +} + +// Driver Code +int main() +{ + // Start with the empty list + struct Node* head = NULL; + + // Iterate and add element + for (int i=5; i>0; i--) + { + push(&head, i); + printList(head); + printMiddle(head); + } + + return 0; +} diff --git a/Reverse a linked list b/Reverse a linked list new file mode 100644 index 0000000..d3620be --- /dev/null +++ b/Reverse a linked list @@ -0,0 +1,82 @@ +// Iterative C++ program to reverse +// a linked list +#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 program to test above function*/ +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; +}