Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions Middle of Linked List
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include<bits/stdc++.h>
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;
}
82 changes: 82 additions & 0 deletions Reverse a linked list
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Iterative C++ program to reverse
// a linked list
#include <iostream>
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;
}