code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
// C++ program Count total number of sub-arrays
// having total distinct elements same as that
// original array.
#include<bits/stdc++.h>
using namespace std;
// Function to calculate distinct sub-array
int countDistictSubarray(int arr[], int n)
{
// Count distinct elements in whole array
unordered_map<int, int> vis;
for (int i = 0; i < n; ++i)
vis[arr[i]] = 1;
int k = vis.size();
// Reset the container by removing all elements
vis.clear();
// Use sliding window concept to find
// count of subarrays having k distinct
// elements.
int ans = 0, right = 0, window = 0;
for (int left = 0; left < n; ++left)
{
while (right < n && window < k)
{
++vis[ arr[right] ];
if (vis[ arr[right] ] == 1)
++window;
++right;
}
// If window size equals to array distinct
// element size, then update answer
if (window == k)
ans += (n - right + 1);
// Decrease the frequency of previous element
// for next sliding window
--vis[ arr[left] ];
// If frequency is zero then decrease the
// window size
if (vis[ arr[left] ] == 0)
--window;
}
return ans;
}
// Driver code
int main()
{
int arr[] = {2, 1, 3, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << countDistictSubarray(arr, n) <<"n";
return 0;
}
|
linear
|
linear
|
// Make a set of maximum elements from two
// arrays A[] and B[]
#include <bits/stdc++.h>
using namespace std;
void maximizeTheFirstArray(int A[], int B[],
int n)
{
// Create copies of A[] and B[] and sort
// the copies in descending order.
vector<int> temp1(A, A+n);
vector<int> temp2(B, B+n);
sort(temp1.begin(), temp1.end(), greater<int>());
sort(temp2.begin(), temp2.end(), greater<int>());
// Put maximum n distinct elements of
// both sorted arrays in a map.
unordered_map<int, int> m;
int i = 0, j = 0;
while (m.size() < n)
{
if (temp1[i] >= temp2[j])
{
m[temp1[i]]++;
i++;
}
else
{
m[temp2[j]]++;
j++;
}
}
// Copy elements of A[] to that
// are present in hash m.
vector<int> res;
for (int i = 0; i < n; i++)
if (m.find(A[i]) != m.end())
res.push_back(A[i]);
// Copy elements of B[] to that
// are present in hash m. This time
// we also check if the element did
// not appear twice.
for (int i = 0; i < n; i++)
if (m.find(B[i]) != m.end() &&
m[B[i]] == 1)
res.push_back(B[i]);
// print result
for (int i = 0; i < n; i++)
cout << res[i] << " ";
}
// driver program
int main()
{
int A[] = { 9, 7, 2, 3, 6 };
int B[] = { 7, 4, 8, 0, 1 };
int n = sizeof(A) / sizeof(A[0]);
maximizeTheFirstArray(A, B, n);
return 0;
}
|
linear
|
nlogn
|
// C++ implementation to find the maximum number
// of chocolates to be distributed equally among
// k students
#include <bits/stdc++.h>
using namespace std;
// function to find the maximum number of chocolates
// to be distributed equally among k students
int maxNumOfChocolates(int arr[], int n, int k)
{
// unordered_map 'um' implemented as
// hash table
unordered_map<int, int> um;
// 'sum[]' to store cumulative sum, where
// sum[i] = sum(arr[0]+..arr[i])
int sum[n], curr_rem;
// to store sum of sub-array having maximum sum
int maxSum = 0;
// building up 'sum[]'
sum[0] = arr[0];
for (int i = 1; i < n; i++)
sum[i] = sum[i - 1] + arr[i];
// traversing 'sum[]'
for (int i = 0; i < n; i++) {
// finding current remainder
curr_rem = sum[i] % k;
// if true then sum(0..i) is divisible
// by k
if (curr_rem == 0) {
// update 'maxSum'
if (maxSum < sum[i])
maxSum = sum[i];
}
// if value 'curr_rem' not present in 'um'
// then store it in 'um' with index of its
// first occurrence
else if (um.find(curr_rem) == um.end())
um[curr_rem] = i;
else
// if true, then update 'max'
if (maxSum < (sum[i] - sum[um[curr_rem]]))
maxSum = sum[i] - sum[um[curr_rem]];
}
// required maximum number of chocolates to be
// distributed equally among 'k' students
return (maxSum / k);
}
// Driver program to test above
int main()
{
int arr[] = { 2, 7, 6, 1, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << "Maximum number of chocolates: "
<< maxNumOfChocolates(arr, n, k);
return 0;
}
|
linear
|
linear
|
// C++ program to print n-th number in Recaman's
// sequence
#include <bits/stdc++.h>
using namespace std;
// Prints first n terms of Recaman sequence
int recaman(int n)
{
// Create an array to store terms
int arr[n];
// First term of the sequence is always 0
arr[0] = 0;
printf("%d, ", arr[0]);
// Fill remaining terms using recursive
// formula.
for (int i=1; i< n; i++)
{
int curr = arr[i-1] - i;
int j;
for (j = 0; j < i; j++)
{
// If arr[i-1] - i is negative or
// already exists.
if ((arr[j] == curr) || curr < 0)
{
curr = arr[i-1] + i;
break;
}
}
arr[i] = curr;
printf("%d, ", arr[i]);
}
}
// Driver code
int main()
{
int n = 17;
recaman(n);
return 0;
}
|
linear
|
quadratic
|
// C++ program to print n-th number in Recaman's
// sequence
#include <bits/stdc++.h>
using namespace std;
// Prints first n terms of Recaman sequence
void recaman(int n)
{
if (n <= 0)
return;
// Print first term and store it in a hash
printf("%d, ", 0);
unordered_set<int> s;
s.insert(0);
// Print remaining terms using recursive
// formula.
int prev = 0;
for (int i=1; i< n; i++)
{
int curr = prev - i;
// If arr[i-1] - i is negative or
// already exists.
if (curr < 0 || s.find(curr) != s.end())
curr = prev + i;
s.insert(curr);
printf("%d, ", curr);
prev = curr;
}
}
// Driver code
int main()
{
int n = 17;
recaman(n);
return 0;
}
|
linear
|
linear
|
#include <bits/stdc++.h>
using namespace std;
void findFibSubset(int arr[], int n)
{
for (int i = 0; i < n; i++) {
int fact1 = 5 * pow(arr[i], 2) + 4;
int fact2 = 5 * pow(arr[i], 2) - 4;
if ((int)pow((int)pow(fact1, 0.5), 2) == fact1
|| (int)pow((int)pow(fact2, 0.5), 2) == fact2)
cout << arr[i] << " ";
}
}
int main()
{
int arr[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
int n = 9;
findFibSubset(arr, n);
}
// This code is contributed by garg28harsh.
|
constant
|
linear
|
// C++ program to find largest Fibonacci subset
#include<bits/stdc++.h>
using namespace std;
// Prints largest subset of an array whose
// all elements are fibonacci numbers
void findFibSubset(int arr[], int n)
{
// Find maximum element in arr[]
int max = *std::max_element(arr, arr+n);
// Generate all Fibonacci numbers till
// max and store them in hash.
int a = 0, b = 1;
unordered_set<int> hash;
hash.insert(a);
hash.insert(b);
while (b < max)
{
int c = a + b;
a = b;
b = c;
hash.insert(b);
}
// Npw iterate through all numbers and
// quickly check for Fibonacci using
// hash.
for (int i=0; i<n; i++)
if (hash.find(arr[i]) != hash.end())
printf("%d ", arr[i]);
}
// Driver code
int main()
{
int arr[] = {4, 2, 8, 5, 20, 1, 40, 13, 23};
int n = sizeof(arr)/sizeof(arr[0]);
findFibSubset(arr, n);
return 0;
}
|
linear
|
linear
|
// C++ program to find averages of all levels
// in a binary tree.
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node {
int data;
struct Node* left, *right;
};
string inorder(Node* node, unordered_map<string, int>& m)
{
if (!node)
return "";
string str = "(";
str += inorder(node->left, m);
str += to_string(node->data);
str += inorder(node->right, m);
str += ")";
// Subtree already present (Note that we use
// unordered_map instead of unordered_set
// because we want to print multiple duplicates
// only once, consider example of 4 in above
// subtree, it should be printed only once.
if (m[str] == 1)
cout << node->data << " ";
m[str]++;
return str;
}
// Wrapper over inorder()
void printAllDups(Node* root)
{
unordered_map<string, int> m;
inorder(root, m);
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(2);
root->right->left->left = newNode(4);
root->right->right = newNode(4);
printAllDups(root);
return 0;
}
|
quadratic
|
quadratic
|
// A brute force approach based CPP program to
// find if there is a rectangle with 1 as corners.
#include <bits/stdc++.h>
using namespace std;
// Returns true if there is a rectangle with
// 1 as corners.
bool isRectangle(const vector<vector<int> >& m)
{
// finding row and column size
int rows = m.size();
if (rows == 0)
return false;
int columns = m[0].size();
// scanning the matrix
for (int y1 = 0; y1 < rows; y1++)
for (int x1 = 0; x1 < columns; x1++)
// if any index found 1 then try
// for all rectangles
if (m[y1][x1] == 1)
for (int y2 = y1 + 1; y2 < rows; y2++)
for (int x2 = x1 + 1; x2 < columns; x2++)
if (m[y1][x2] == 1 && m[y2][x1] == 1 &&
m[y2][x2] == 1)
return true;
return false;
}
// Driver code
int main()
{
vector<vector<int> > mat = { { 1, 0, 0, 1, 0 },
{ 0, 0, 1, 0, 1 },
{ 0, 0, 0, 1, 0 },
{ 1, 0, 1, 0, 1 } };
if (isRectangle(mat))
cout << "Yes";
else
cout << "No";
}
|
constant
|
quadratic
|
// An efficient approach based CPP program to
// find if there is a rectangle with 1 as
// corners.
#include <bits/stdc++.h>
using namespace std;
// Returns true if there is a rectangle with
// 1 as corners.
bool isRectangle(const vector<vector<int> >& matrix)
{
// finding row and column size
int rows = matrix.size();
if (rows == 0)
return false;
int columns = matrix[0].size();
// map for storing the index of combination of 2 1's
unordered_map<int, unordered_set<int> > table;
// scanning from top to bottom line by line
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns - 1; ++j) {
for (int k = j + 1; k < columns; ++k) {
// if found two 1's in a column
if (matrix[i][j] == 1 && matrix[i][k] == 1) {
// check if there exists 1's in same
// row previously then return true
// we don't need to check (j, k) pair
// and again (k, j) pair because we always
// store pair in ascending order and similarly
// check in ascending order, i.e. j always less
// than k.
if (table.find(j) != table.end()
&& table[j].find(k) != table[j].end())
return true;
// store the indexes in hashset
table[j].insert(k);
}
}
}
}
return false;
}
// Driver code
int main()
{
vector<vector<int> > mat = { { 1, 0, 0, 1, 0 },
{ 0, 1, 1, 1, 1 },
{ 0, 0, 0, 1, 0 },
{ 1, 1, 1, 1, 0 } };
if (isRectangle(mat))
cout << "Yes";
else
cout << "No";
}
// This code is improved by Gautam Agrawal
|
quadratic
|
quadratic
|
// C++ implementation comes from:
// https://github.com/MichaelWehar/FourCornersProblem
// Written by Niteesh Kumar and Michael Wehar
// References:
// [1] F. Mráz, D. Prusa, and M. Wehar.
// Two-dimensional Pattern Matching against
// Basic Picture Languages. CIAA 2019.
// [2] D. Prusa and M. Wehar. Complexity of
// Searching for 2 by 2 Submatrices in Boolean
// Matrices. DLT 2020.
#include <bits/stdc++.h>
using namespace std;
bool searchForRectangle(int rows, int cols,
vector<vector<int>> mat)
{
// Make sure that matrix is non-trivial
if (rows < 2 || cols < 2)
{
return false;
}
// Create map
int num_of_keys;
map<int, vector<int>> adjsList;
if (rows >= cols)
{
// Row-wise
num_of_keys = rows;
// Convert each row into vector of col indexes
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (mat[i][j])
{
adjsList[i].push_back(j);
}
}
}
}
else
{
// Col-wise
num_of_keys = cols;
// Convert each col into vector of row indexes
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (mat[i][j])
{
adjsList[j].push_back(i);
}
}
}
}
// Search for a rectangle whose four corners are 1's
map<pair<int, int>, int> pairs;
for (int i = 0; i < num_of_keys; i++)
{
vector<int> values = adjsList[i];
int size = values.size();
for (int j = 0; j < size - 1; j++)
{
for (int k = j + 1; k < size; k++)
{
pair<int, int> temp
= make_pair(values[j],
values[k]);
if (pairs.find(temp)
!= pairs.end())
{
return true;
} else {
pairs[temp] = i;
}
}
}
}
return false;
}
// Driver code
int main()
{
vector<vector<int> > mat = { { 1, 0, 0, 1, 0 },
{ 0, 1, 1, 1, 1 },
{ 0, 0, 0, 1, 0 },
{ 1, 1, 1, 1, 0 } };
if (searchForRectangle(4, 5, mat))
cout << "Yes";
else
cout << "No";
}
|
quadratic
|
quadratic
|
// CPP program for finding maximum area possible
// of a rectangle
#include <bits/stdc++.h>
using namespace std;
// function for finding max area
int findArea(int arr[], int n)
{
// sort array in non-increasing order
sort(arr, arr + n, greater<int>());
// Initialize two sides of rectangle
int dimension[2] = { 0, 0 };
// traverse through array
for (int i = 0, j = 0; i < n - 1 && j < 2; i++)
// if any element occurs twice
// store that as dimension
if (arr[i] == arr[i + 1])
dimension[j++] = arr[i++];
// return the product of dimensions
return (dimension[0] * dimension[1]);
}
// driver function
int main()
{
int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findArea(arr, n);
return 0;
}
|
constant
|
nlogn
|
// CPP program for finding maximum area possible
// of a rectangle
#include <bits/stdc++.h>
using namespace std;
// function for finding max area
int findArea(int arr[], int n)
{
unordered_set<int> s;
// traverse through array
int first = 0, second = 0;
for (int i = 0; i < n; i++) {
// If this is first occurrence of arr[i],
// simply insert and continue
if (s.find(arr[i]) == s.end()) {
s.insert(arr[i]);
continue;
}
// If this is second (or more) occurrence,
// update first and second maximum values.
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second)
second = arr[i];
}
// return the product of dimensions
return (first * second);
}
// driver function
int main()
{
int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findArea(arr, n);
return 0;
}
|
linear
|
linear
|
// C++ implementation to find length of longest
// strict bitonic subsequence
#include <bits/stdc++.h>
using namespace std;
// function to find length of longest
// strict bitonic subsequence
int longLenStrictBitonicSub(int arr[], int n)
{
// hash table to map the array element with the
// length of the longest subsequence of which
// it is a part of and is the last/first element of
// that subsequence
unordered_map<int, int> inc, dcr;
// arrays to store the length of increasing and
// decreasing subsequences which end at them
// or start from them
int len_inc[n], len_dcr[n];
// to store the length of longest strict
// bitonic subsequence
int longLen = 0;
// traverse the array elements
// from left to right
for (int i=0; i<n; i++)
{
// initialize current length
// for element arr[i] as 0
int len = 0;
// if 'arr[i]-1' is in 'inc'
if (inc.find(arr[i]-1) != inc.end())
len = inc[arr[i]-1];
// update arr[i] subsequence length in 'inc'
// and in len_inc[]
inc[arr[i]] = len_inc[i] = len + 1;
}
// traverse the array elements
// from right to left
for (int i=n-1; i>=0; i--)
{
// initialize current length
// for element arr[i] as 0
int len = 0;
// if 'arr[i]-1' is in 'dcr'
if (dcr.find(arr[i]-1) != dcr.end())
len = dcr[arr[i]-1];
// update arr[i] subsequence length in 'dcr'
// and in len_dcr[]
dcr[arr[i]] = len_dcr[i] = len + 1;
}
// calculating the length of all the strict
// bitonic subsequence
for (int i=0; i<n; i++)
if (longLen < (len_inc[i] + len_dcr[i] - 1))
longLen = len_inc[i] + len_dcr[i] - 1;
// required longest length strict
// bitonic subsequence
return longLen;
}
// Driver program to test above
int main()
{
int arr[] = {1, 5, 2, 3, 4, 5, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Longest length strict bitonic subsequence = "
<< longLenStrictBitonicSub(arr, n);
return 0;
}
|
linear
|
linear
|
// C++ program to find last seen element in
// an array.
#include <bits/stdc++.h>
using namespace std;
// Returns last seen element in arr[]
int lastSeenElement(int a[], int n)
{
// Store last occurrence index of
// every element
unordered_map<int, int> hash;
for (int i = 0; i < n; i++)
hash[a[i]] = i;
// Find an element in hash with minimum
// index value
int res_ind = INT_MAX, res;
for (auto x : hash)
{
if (x.second < res_ind)
{
res_ind = x.second;
res = x.first;
}
}
return res;
}
// driver program
int main()
{
int a[] = { 2, 1, 2, 2, 4, 1 };
int n = sizeof(a) / sizeof(a[0]);
cout << lastSeenElement(a, n);
return 0;
}
|
linear
|
linear
|
// A complete working C++ program to
// demonstrate all insertion methods
// on Linked List
#include <bits/stdc++.h>
using namespace std;
// A linked list node
class Node
{
public:
int data;
Node *next;
};
// Given a reference (pointer to pointer)
// to the head of a list and an int, inserts
// a new node on the front of the list.
void push(Node** head_ref, int new_data)
{
// 1. allocate node
Node* new_node = new Node();
// 2. put in the data
new_node->data = new_data;
// 3. Make next of new node as head
new_node->next = (*head_ref);
// 4. move the head to point
// to the new node
(*head_ref) = new_node;
}
// Given a node prev_node, insert a new
// node after the given prev_node
void insertAfter(Node* prev_node, int new_data)
{
// 1. check if the given prev_node
// is NULL
if (prev_node == NULL)
{
cout<<"The given previous node cannot be NULL";
return;
}
// 2. allocate new node
Node* new_node = new Node();
// 3. put in the data
new_node->data = new_data;
// 4. Make next of new node
// as next of prev_node
new_node->next = prev_node->next;
// 5. move the next of prev_node
// as new_node
prev_node->next = new_node;
}
// Given a reference (pointer to pointer)
// to the head of a list and an int,
// appends a new node at the end
void append(Node** head_ref, int new_data)
{
// 1. allocate node
Node* new_node = new Node();
//used in step 5
Node *last = *head_ref;
// 2. put in the data
new_node->data = new_data;
/* 3. This new node is going to be
the last node, so make next of
it as NULL*/
new_node->next = NULL;
/* 4. If the Linked List is empty,
then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last->next != NULL)
{
last = last->next;
}
/* 6. Change the next of last node */
last->next = new_node;
return;
}
// This function prints contents of
// linked list starting from head
void printList(Node *node)
{
while (node != NULL)
{
cout<<" "<<node->data;
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty list
Node* head = NULL;
// Insert 6. So linked list becomes 6->NULL
append(&head, 6);
// Insert 7 at the beginning.
// So linked list becomes 7->6->NULL
push(&head, 7);
// Insert 1 at the beginning.
// So linked list becomes 1->7->6->NULL
push(&head, 1);
// Insert 4 at the end. So
// linked list becomes 1->7->6->4->NULL
append(&head, 4);
// Insert 8, after 7. So linked
// list becomes 1->7->8->6->4->NULL
insertAfter(head->next, 8);
cout<<"Created Linked list is: ";
printList(head);
return 0;
}
// This code is contributed by rathbhupendra, arkajyotibasak
|
constant
|
linear
|
// Alternate method to declare the class
// in order to minimize the
// memory allocation work
#include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node* next;
// A constructor is called here
node(int value)
{
// It automatically assigns the
// value to the data
data = value;
// Next pointer is pointed to NULL
next = NULL;
}
};
// Function to insert an element
// at head position
void insertathead(node*& head, int val)
{
node* n = new node(val);
n->next = head;
head = n;
}
// Function to insert a element
// at a specified position
void insertafter(node* head, int key, int val)
{
node* n = new node(val);
if (key == head->data) {
n->next = head->next;
head->next = n;
return;
}
node* temp = head;
while (temp->data != key) {
temp = temp->next;
if (temp == NULL) {
return;
}
}
n->next = temp->next;
temp->next = n;
}
// Function to insert an
// element at the end
void insertattail(node*& head, int val)
{
node* n = new node(val);
if (head == NULL) {
head = n;
return;
}
node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = n;
}
// Function to print the
// singly linked list
void print(node*& head)
{
node* temp = head;
while (temp != NULL) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
// Main function
int main()
{
// Declaring an empty linked list
node* head = NULL;
insertathead(head, 1);
insertathead(head, 2);
cout << "After insertion at head: ";
print(head);
cout << endl;
insertattail(head, 4);
insertattail(head, 5);
cout << "After insertion at tail: ";
print(head);
cout << endl;
insertafter(head, 1, 2);
insertafter(head, 5, 6);
cout << "After insertion at a given position: ";
print(head);
cout << endl;
return 0;
}
// contributed by divyanshmishra101010
|
constant
|
linear
|
// A complete working C++ program to delete
// a node in a linked list at a given position
#include <iostream>
using namespace std;
// A linked list node
class Node {
public:
int data;
Node* next;
};
// Given a reference (pointer to pointer) to
// the head of a list and an int inserts a
// new node on the front of the list.
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
// Given a reference (pointer to pointer) to
// the head of a list and a position, deletes
// the node at the given position
void deleteNode(Node** head_ref, int position)
{
// If linked list is empty
if (*head_ref == NULL)
return;
// Store head node
Node* temp = *head_ref;
// If head needs to be removed
if (position == 0) {
// Change head
*head_ref = temp->next;
// Free old head
free(temp);
return;
}
// Find previous node of the node to be deleted
for (int i = 0; temp != NULL && i < position - 1; i++)
temp = temp->next;
// If position is more than number of nodes
if (temp == NULL || temp->next == NULL)
return;
// Node temp->next is the node to be deleted
// Store pointer to the next of node to be deleted
Node* next = temp->next->next;
// Unlink the node from linked list
free(temp->next); // Free memory
// Unlink the deleted node from list
temp->next = next;
}
// This function prints contents of linked
// list starting from the given node
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty list
Node* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
push(&head, 8);
cout << "Created Linked List: ";
printList(head);
deleteNode(&head, 4);
cout << "\nLinked List after Deletion at position 4: ";
printList(head);
return 0;
}
// This code is contributed by premsai2030
|
constant
|
linear
|
// C++ program to delete a linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
/* Function to delete the entire linked list */
void deleteList(Node** head_ref)
{
/* deref head_ref to get the real head */
Node* current = *head_ref;
Node* next = NULL;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
/* deref head_ref to affect the real head back
in the caller. */
*head_ref = NULL;
}
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
/* allocate node */
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;
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Use push() to construct below list
1->12->1->4->1 */
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
cout << "Deleting linked list";
deleteList(&head);
cout << "\nLinked list deleted";
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
// Iterative C++ program to find length
// or count of nodes in a linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Counts no. of nodes in linked list */
int getCount(Node* head)
{
int count = 0; // Initialize count
Node* current = head; // Initialize current
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
// Function call
cout << "count of nodes is " << getCount(head);
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
// Recursive C++ program to find length
// or count of nodes in a linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Recursively count number of nodes in linked list */
int getCount(Node* head)
{
// Base Case
if (head == NULL) {
return 0;
}
// Count this node plus the rest of the list
else {
return 1 + getCount(head->next);
}
}
/* Driver program to test count function*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
/* Check the count function */
cout << "Count of nodes is " << getCount(head);
return 0;
}
// This is code is contributed by rajsanghavi9
|
linear
|
linear
|
// Tail Recursive C++ program to find length
// or count of nodes in a linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
/* allocate node */
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 tail recursive function to count the nodes of a linked
// list
// default value of the count is used as zero
int getCount(Node* head, int count = 0)
{
// base case
if (head == NULL)
return count;
// move the pointer to next node and increase the count
return getCount(head->next, count + 1);
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
// Function call
cout << "Count of nodes is " << getCount(head);
return 0;
}
// This is code is contributed by Abhijeet Kumar
|
constant
|
linear
|
// Iterative C++ program to search
// an element in linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int key;
Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_key)
{
/* allocate node */
Node* new_node = new Node();
/* put in the key */
new_node->key = new_key;
/* 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;
}
/* Checks whether the value x is present in linked list */
bool search(Node* head, int x)
{
Node* current = head; // Initialize current
while (current != NULL) {
if (current->key == x)
return true;
current = current->next;
}
return false;
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
int x = 21;
/* Use push() to construct below list
14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
// Function call
search(head, 21) ? cout << "Yes" : cout << "No";
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
// Recursive C++ program to search
// an element in linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int key;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_key)
{
/* allocate node */
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
/* put in the key */
new_node->key = new_key;
/* 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;
}
/* Checks whether the value x is present in linked list */
bool search(struct Node* head, int x)
{
// Base case
if (head == NULL)
return false;
// If key is present in current node, return true
if (head->key == x)
return true;
// Recur for remaining list
return search(head->next, x);
}
/* Driver code*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
int x = 21;
/* Use push() to construct below list
14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
// Function call
search(head, 21) ? cout << "Yes" : cout << "No";
return 0;
}
// This code is contributed by SHUBHAMSINGH10
|
linear
|
linear
|
// C++ program to find n'th node in linked list
// using recursion
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node {
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to
the head of a list and an int, push a
new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node
= (struct Node*)malloc(sizeof(struct 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;
}
/* Takes head pointer of the linked list and index
as arguments and return data at index. (Don't use
another variable)*/
int GetNth(struct Node* head, int n)
{
// if length of the list is less
// than the given index, return -1
if (head == NULL)
return -1;
// if n equal to 0 return node->data
if (n == 0)
return head->data;
// increase head to next pointer
// n - 1: decrease the number of recursions until n = 0
return GetNth(head->next, n - 1);
}
/* Driver code*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() to construct below list
1->12->1->4->1 */
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
/* Check the count function */
printf("Element at index 3 is %d", GetNth(head, 3));
getchar();
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
linear
|
linear
|
// C++ program to find N'th node from end
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* Function to get the Nth node from
the last of a linked list*/
void printNthFromLast(struct Node* head, int N)
{
int len = 0, i;
struct Node* temp = head;
// Count the number of nodes in Linked List
while (temp != NULL) {
temp = temp->next;
len++;
}
// Check if value of N is not
// more than length of the linked list
if (len < N)
return;
temp = head;
// Get the (len-N+1)th node from the beginning
for (i = 1; i < len - N + 1; i++)
temp = temp->next;
cout << temp->data;
return;
}
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 of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// Driver's Code
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
// create linked 35->15->4->20
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 35);
// Function call
printNthFromLast(head, 4);
return 0;
}
|
constant
|
linear
|
// C++ program to find n-th node
// from the end of the linked list.
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* next;
node(int val)
{
data = val;
next = NULL;
}
};
struct llist {
node* head;
llist() { head = NULL; }
// insert operation at the beginning of the list.
void insertAtBegin(int val)
{
node* newNode = new node(val);
newNode->next = head;
head = newNode;
}
// finding n-th node from the end.
void nthFromEnd(int n)
{
// create two pointers main_ptr and ref_ptr
// initially pointing to head.
node* main_ptr = head;
node* ref_ptr = head;
// if list is empty, return
if (head == NULL) {
cout << "List is empty" << endl;
return;
}
// move ref_ptr to the n-th node from beginning.
for (int i = 1; i < n; i++) {
ref_ptr = ref_ptr->next;
if (ref_ptr == NULL) {
cout << n
<< " is greater than no. of nodes in "
"the list"
<< endl;
return;
}
}
// move ref_ptr and main_ptr by one node until
// ref_ptr reaches end of the list.
while (ref_ptr != NULL && ref_ptr->next != NULL) {
ref_ptr = ref_ptr->next;
main_ptr = main_ptr->next;
}
cout << "Node no. " << n
<< " from end is: " << main_ptr->data << endl;
}
void displaylist()
{
node* temp = head;
while (temp != NULL) {
cout << temp->data << "->";
temp = temp->next;
}
cout << "NULL" << endl;
}
};
// Driver's code
int main()
{
llist ll;
ll.insertAtBegin(20);
ll.insertAtBegin(4);
ll.insertAtBegin(15);
ll.insertAtBegin(35);
ll.displaylist();
// Function call
ll.nthFromEnd(4);
return 0;
}
// This code is contributed by sandeepkrsuman.
|
constant
|
linear
|
// C++ program for the above approach
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
class NodeOperation{
public:
// Function to add a new node
void pushNode(class Node** head_ref,int data_val){
// Allocate node
class Node *new_node = new Node();
// Put in the data
new_node->data = data_val;
// 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 printNode(class Node *head){
while(head != NULL){
cout <<head->data << "->";
head = head->next;
}
cout << "NULL" << endl;
}
void printMiddle(class 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;
}
cout << "The middle element is [" << slow_ptr->data << "]" << endl;
}
}
};
// Driver Code
int main(){
class Node *head = NULL;
class NodeOperation *temp = new NodeOperation();
for(int i=5; i>0; i--){
temp->pushNode(&head, i);
temp->printNode(head);
temp->printMiddle(head);
}
return 0;
}
|
constant
|
linear
|
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct node
{
int data;
struct node* next;
};
// Function to get the middle of
// the linked list
void printMiddle(struct node* head)
{
int count = 0;
struct node* mid = head;
while (head != NULL)
{
// Update mid, when 'count'
// is odd number
if (count & 1)
mid = mid->next;
++count;
head = head->next;
}
// If empty list is provided
if (mid != NULL)
printf("The middle element is [%d]\n\n",
mid->data);
}
void push(struct node** head_ref, int new_data)
{
// Allocate node
struct node* new_node = (struct node*)malloc(
sizeof(struct 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;
int i;
for(i = 5; i > 0; i--)
{
push(&head, i);
printList(head);
printMiddle(head);
}
return 0;
}
// This code is contributed by ac121102
|
constant
|
linear
|
// C++ program to count occurrences in a linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
/* allocate node */
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;
}
/* Counts the no. of occurrences of a node
(search_for) in a linked list (head)*/
int count(Node* head, int search_for)
{
Node* current = head;
int count = 0;
while (current != NULL) {
if (current->data == search_for)
count++;
current = current->next;
}
return count;
}
/* Driver program to test count function*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
/* Check the count function */
cout << "count of 1 is " << count(head, 1);
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
// C++ program to count occurrences in a linked list using
// recursion
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
// global variable for counting frequency of
// given element k
int frequency = 0;
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node
= (struct Node*)malloc(sizeof(struct 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;
}
/* Counts the no. of occurrences of a node
(search_for) in a linked list (head)*/
int count(struct Node* head, int key)
{
if (head == NULL)
return frequency;
if (head->data == key)
frequency++;
return count(head->next, key);
}
/* Driver program to test count function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
/* Check the count function */
cout << "count of 1 is " << count(head, 1);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
linear
|
linear
|
// C++ program to count number of nodes
// in loop in a linked list if loop is
// present
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
// Returns count of nodes present in loop.
int countNodes(struct Node* n)
{
int res = 1;
struct Node* temp = n;
while (temp->next != n) {
res++;
temp = temp->next;
}
return res;
}
/* This function detects and counts loop
nodes in the list. If loop is not there
then returns 0 */
int countNodesinLoop(struct Node* list)
{
struct Node *slow_p = list, *fast_p = list;
while (slow_p && fast_p && fast_p->next) {
slow_p = slow_p->next;
fast_p = fast_p->next->next;
/* If slow_p and fast_p meet at
some point then there is a loop */
if (slow_p == fast_p)
return countNodes(slow_p);
}
/* Return 0 to indicate that
there is no loop*/
return 0;
}
struct Node* newNode(int key)
{
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
// Driver Code
int main()
{
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
/* Create a loop for testing */
head->next->next->next->next->next = head->next;
cout << countNodesinLoop(head) << endl;
return 0;
}
// This code is contributed by SHUBHAMSINGH10
|
constant
|
linear
|
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node(int d) { data = d; }
Node* ptr;
};
// Function to check if the linked list
// is palindrome or not
bool isPalin(Node* head)
{
// Temp pointer
Node* slow = head;
// Declare a stack
stack<int> s;
// Push all elements of the list
// to the stack
while (slow != NULL) {
s.push(slow->data);
// Move ahead
slow = slow->ptr;
}
// Iterate in the list again and
// check by popping from the stack
while (head != NULL) {
// Get the top most element
int i = s.top();
// Pop the element
s.pop();
// Check if data is not
// same as popped element
if (head->data != i) {
return false;
}
// Move ahead
head = head->ptr;
}
return true;
}
// Driver Code
int main()
{
// Addition of linked list
Node one = Node(1);
Node two = Node(2);
Node three = Node(3);
Node four = Node(2);
Node five = Node(1);
// Initialize the next pointer
// of every current pointer
five.ptr = NULL;
one.ptr = &two
two.ptr = &three
three.ptr = &four
four.ptr = &five
Node* temp = &one
// Call function to check palindrome or not
int result = isPalin(&one);
if (result == 1)
cout << "isPalindrome is true\n";
else
cout << "isPalindrome is false\n";
return 0;
}
// This code has been contributed by Striver
|
linear
|
linear
|
// C++ program to check if a linked list is palindrome
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node {
char data;
struct Node* next;
};
void reverse(struct Node**);
bool compareLists(struct Node*, struct Node*);
// Function to check if given linked list is
// palindrome or not
bool isPalindrome(struct Node* head)
{
struct Node *slow_ptr = head, *fast_ptr = head;
struct Node *second_half, *prev_of_slow_ptr = head;
// To handle odd size list
struct Node* midnode = NULL;
// initialize result
bool res = true;
if (head != NULL && head->next != NULL) {
// Get the middle of the list. Move slow_ptr by 1
// and fast_ptr by 2, slow_ptr will have the middle
// node
while (fast_ptr != NULL && fast_ptr->next != NULL) {
fast_ptr = fast_ptr->next->next;
// We need previous of the slow_ptr for
// linked lists with odd elements
prev_of_slow_ptr = slow_ptr;
slow_ptr = slow_ptr->next;
}
// fast_ptr would become NULL when there
// are even elements in list. And not NULL
// for odd elements. We need to skip the
// middle node for odd case and store it
// somewhere so that we can restore the
// original list
if (fast_ptr != NULL) {
midnode = slow_ptr;
slow_ptr = slow_ptr->next;
}
// Now reverse the second half and
// compare it with first half
second_half = slow_ptr;
// NULL terminate first half
prev_of_slow_ptr->next = NULL;
// Reverse the second half
reverse(&second_half);
// compare
res = compareLists(head, second_half);
// Construct the original list back
reverse(
&second_half); // Reverse the second half again
// If there was a mid node (odd size case)
// which was not part of either first half
// or second half.
if (midnode != NULL) {
prev_of_slow_ptr->next = midnode;
midnode->next = second_half;
}
else
prev_of_slow_ptr->next = second_half;
}
return res;
}
// Function to reverse the linked list
// Note that this function may change
// the head
void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
// Function to check if two input
// lists have same data
bool compareLists(struct Node* head1, struct Node* head2)
{
struct Node* temp1 = head1;
struct Node* temp2 = head2;
while (temp1 && temp2) {
if (temp1->data == temp2->data) {
temp1 = temp1->next;
temp2 = temp2->next;
}
else
return 0;
}
// Both are empty return 1
if (temp1 == NULL && temp2 == NULL)
return 1;
// Will reach here when one is NULL
// and other is not
return 0;
}
// Push a node to linked list. Note
// that this function changes the head
void push(struct Node** head_ref, char new_data)
{
// Allocate node
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
// Put in the data
new_node->data = new_data;
// Link the old list of 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) {
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL"
<< "\n";
}
// Driver code
int main()
{
// Start with the empty list
struct Node* head = NULL;
char str[] = "abacaba";
int i;
for (i = 0; str[i] != '\0'; i++) {
push(&head, str[i]);
}
isPalindrome(head) ? cout << "Is Palindrome"
<< "\n\n"
: cout << "Not Palindrome"
<< "\n\n";
return 0;
}
// This code is contributed by Shivani
|
constant
|
linear
|
// Recursive program to check if a given linked list is
// palindrome
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct node {
char data;
struct node* next;
};
// Initial parameters to this function are &head and head
bool isPalindromeUtil(struct node** left,
struct node* right)
{
/* stop recursion when right becomes NULL */
if (right == NULL)
return true;
/* If sub-list is not palindrome then no need to
check for current left and right, return false */
bool isp = isPalindromeUtil(left, right->next);
if (isp == false)
return false;
/* Check values at current left and right */
bool isp1 = (right->data == (*left)->data);
/* Move left to next node */
*left = (*left)->next;
return isp1;
}
// A wrapper over isPalindromeUtil()
bool isPalindrome(struct node* head)
{
return isPalindromeUtil(&head, head);
}
/* Push a node to linked list. Note that this function
changes the head */
void push(struct node** head_ref, char new_data)
{
/* allocate node */
struct node* new_node
= (struct node*)malloc(sizeof(struct 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) {
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL\n";
}
/* Driver program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
char str[] = "abacaba";
int i;
for (i = 0; str[i] != '\0'; i++) {
push(&head, str[i]);
}
isPalindrome(head) ? cout << "Is Palindrome\n\n"
: cout << "Not Palindrome\n\n";
return 0;
}
// this code is contributed by shivanisinghss2110
|
linear
|
linear
|
/* C++ Program to remove duplicates in an unsorted
linked list */
#include <bits/stdc++.h>
using namespace std;
/* A linked list node */
struct Node {
int data;
struct Node* next;
};
// Utility function to create a new Node
struct Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* Function to remove duplicates from a
unsorted linked list */
void removeDuplicates(struct Node* start)
{
struct Node *ptr1, *ptr2, *dup;
ptr1 = start;
/* Pick elements one by one */
while (ptr1 != NULL && ptr1->next != NULL) {
ptr2 = ptr1;
/* Compare the picked element with rest
of the elements */
while (ptr2->next != NULL) {
/* If duplicate then delete it */
if (ptr1->data == ptr2->next->data) {
/* sequence of steps is important here */
dup = ptr2->next;
ptr2->next = ptr2->next->next;
delete (dup);
}
else /* This is tricky */
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
}
/* Function to print nodes in a given linked list */
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
// Driver code
int main()
{
/* The constructed linked list is:
10->12->11->11->12->11->10*/
struct Node* start = newNode(10);
start->next = newNode(12);
start->next->next = newNode(11);
start->next->next->next = newNode(11);
start->next->next->next->next = newNode(12);
start->next->next->next->next->next = newNode(11);
start->next->next->next->next->next->next = newNode(10);
printf("Linked list before removing duplicates ");
printList(start);
removeDuplicates(start);
printf("\nLinked list after removing duplicates ");
printList(start);
return 0;
}
|
constant
|
quadratic
|
/* This program swaps the nodes of linked list rather
than swapping the field from the nodes.*/
#include <bits/stdc++.h>
using namespace std;
/* A linked list node */
class Node {
public:
int data;
Node* next;
};
/* Function to swap nodes x and y in linked list by
changing links */
void swapNodes(Node** head_ref, int x, int y)
{
// Nothing to do if x and y are same
if (x == y)
return;
// Search for x (keep track of prevX and CurrX
Node *prevX = NULL, *currX = *head_ref;
while (currX && currX->data != x) {
prevX = currX;
currX = currX->next;
}
// Search for y (keep track of prevY and CurrY
Node *prevY = NULL, *currY = *head_ref;
while (currY && currY->data != y) {
prevY = currY;
currY = currY->next;
}
// If either x or y is not present, nothing to do
if (currX == NULL || currY == NULL)
return;
// If x is not head of linked list
if (prevX != NULL)
prevX->next = currY;
else // Else make y as new head
*head_ref = currY;
// If y is not head of linked list
if (prevY != NULL)
prevY->next = currX;
else // Else make x as new head
*head_ref = currX;
// Swap next pointers
Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
}
/* Function to add a node at the beginning of List */
void push(Node** head_ref, int new_data)
{
/* allocate node */
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;
}
/* Function to print nodes in a given linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
/* Driver program to test above function */
int main()
{
Node* start = NULL;
/* The constructed linked list is:
1->2->3->4->5->6->7 */
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before calling swapNodes() ";
printList(start);
swapNodes(&start, 4, 3);
cout << "\nLinked list after calling swapNodes() ";
printList(start);
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
// C++ program to swap two given nodes of a linked list
#include <iostream>
using namespace std;
// A linked list node class
class Node {
public:
int data;
class Node* next;
// constructor
Node(int val, Node* next)
: data(val)
, next(next)
{
}
// print list from this to last till null
void printList()
{
Node* node = this;
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
};
// Function to add a node at the beginning of List
void push(Node** head_ref, int new_data)
{
// allocate node
(*head_ref) = new Node(new_data, *head_ref);
}
void swap(Node*& a, Node*& b)
{
Node* temp = a;
a = b;
b = temp;
}
void swapNodes(Node** head_ref, int x, int y)
{
// Nothing to do if x and y are same
if (x == y)
return;
Node **a = NULL, **b = NULL;
// search for x and y in the linked list
// and store their pointer in a and b
while (*head_ref) {
if ((*head_ref)->data == x)
a = head_ref;
else if ((*head_ref)->data == y)
b = head_ref;
head_ref = &((*head_ref)->next);
}
// if we have found both a and b
// in the linked list swap current
// pointer and next pointer of these
if (a && b) {
swap(*a, *b);
swap(((*a)->next), ((*b)->next));
}
}
// Driver code
int main()
{
Node* start = NULL;
// The constructed linked list is:
// 1->2->3->4->5->6->7
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before calling swapNodes() ";
start->printList();
swapNodes(&start, 6, 1);
cout << "Linked list after calling swapNodes() ";
start->printList();
}
// This code is contributed by Sania Kumari Gupta
// (kriSania804)
|
constant
|
linear
|
/* CPP Program to move last element
to front in a given linked list */
#include <bits/stdc++.h>
using namespace std;
/* A linked list node */
class Node {
public:
int data;
Node* next;
};
/* We are using a double pointer
head_ref here because we change
head of the linked list inside
this function.*/
void moveToFront(Node** head_ref)
{
/* If linked list is empty, or
it contains only one node,
then nothing needs to be done,
simply return */
if (*head_ref == NULL || (*head_ref)->next == NULL)
return;
/* Initialize second last
and last pointers */
Node* secLast = NULL;
Node* last = *head_ref;
/*After this loop secLast contains
address of second last node and
last contains address of last node in Linked List */
while (last->next != NULL) {
secLast = last;
last = last->next;
}
/* Set the next of second last as NULL */
secLast->next = NULL;
/* Set next of last as head node */
last->next = *head_ref;
/* Change the head pointer
to point to last node now */
*head_ref = last;
}
/* UTILITY FUNCTIONS */
/* Function to add a node
at the beginning of Linked List */
void push(Node** head_ref, int new_data)
{
/* allocate node */
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;
}
/* Function to print nodes in a given linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
// Driver's code
int main()
{
Node* start = NULL;
/* The constructed linked list is:
1->2->3->4->5 */
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before moving last to front\n";
printList(start);
// Function call
moveToFront(&start);
cout << "\nLinked list after removing last to front\n";
printList(start);
return 0;
}
// This code is contributed by rathbhupendra
|
constant
|
linear
|
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int data;
Node* next;
};
void push(Node** head_ref, int new_data);
/*This solution uses the temporary
dummy to build up the result list */
Node* sortedIntersect(Node* a, Node* b)
{
Node dummy;
Node* tail = &dummy
dummy.next = NULL;
/* Once one or the other
list runs out -- we're done */
while (a != NULL && b != NULL) {
if (a->data == b->data) {
push((&tail->next), a->data);
tail = tail->next;
a = a->next;
b = b->next;
}
/* advance the smaller list */
else if (a->data < b->data)
a = a->next;
else
b = b->next;
}
return (dummy.next);
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at
the beginning of the linked list */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = (Node*)malloc(
sizeof(Node));
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in
a given linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data <<" ";
node = node->next;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty lists */
Node* a = NULL;
Node* b = NULL;
Node* intersect = NULL;
/* Let us create the first sorted
linked list to test the functions
Created linked list will be
1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted linked list
Created linked list will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
/* Find the intersection two linked lists */
intersect = sortedIntersect(a, b);
cout<<"Linked list containing common items of a & b \n";
printList(intersect);
}
|
linear
|
linear
|
// C++ program to implement above approach
#include <bits/stdc++.h>
/* Link list node */
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref,
int new_data);
/* This solution uses the local reference */
struct Node* sortedIntersect(
struct Node* a,
struct Node* b)
{
struct Node* result = NULL;
struct Node** lastPtrRef = &result
/* Advance comparing the first
nodes in both lists.
When one or the other list runs
out, we're done. */
while (a != NULL && b != NULL) {
if (a->data == b->data) {
/* found a node for the intersection */
push(lastPtrRef, a->data);
lastPtrRef = &((*lastPtrRef)->next);
a = a->next;
b = b->next;
}
else if (a->data < b->data)
a = a->next; /* advance the smaller list */
else
b = b->next;
}
return (result);
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the
beginning of the linked list */
void push(struct Node** head_ref,
int new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*)malloc(
sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty lists */
struct Node* a = NULL;
struct Node* b = NULL;
struct Node* intersect = NULL;
/* Let us create the first sorted
linked list to test the functions
Created linked list will be
1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted linked list
Created linked list will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
/* Find the intersection two linked lists */
intersect = sortedIntersect(a, b);
printf("\n Linked list containing common items of a & b \n ");
printList(intersect);
return 0;
}
//This code is contributed by Abhijeet Kumar(abhijeet19403)
|
linear
|
linear
|
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node
{
int data;
struct Node* next;
};
struct Node* sortedIntersect(struct Node* a,
struct Node* b)
{
// base case
if (a == NULL || b == NULL)
return NULL;
/* If both lists are non-empty */
/* Advance the smaller list and
call recursively */
if (a->data < b->data)
return sortedIntersect(a->next, b);
if (a->data > b->data)
return sortedIntersect(a, b->next);
// Below lines are executed only
// when a->data == b->data
struct Node* temp = (struct Node*)malloc(
sizeof(struct Node));
temp->data = a->data;
// Advance both lists and call recursively
temp->next = sortedIntersect(a->next,
b->next);
return temp;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at
the beginning of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* Allocate node */
struct Node* new_node = (struct Node*)malloc(
sizeof(struct Node));
/* Put in the data */
new_node->data = new_data;
/* Link the old list of the new node */
new_node->next = (*head_ref);
/* Move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in
a given linked list */
void printList(struct Node* node)
{
while (node != NULL)
{
cout << " " << node->data;
node = node->next;
}
}
// Driver code
int main()
{
/* Start with the empty lists */
struct Node* a = NULL;
struct Node* b = NULL;
struct Node* intersect = NULL;
/* Let us create the first sorted
linked list to test the functions
Created linked list will be
1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted linked list
Created linked list will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
/* Find the intersection two linked lists */
intersect = sortedIntersect(a, b);
cout << "\n Linked list containing "
<< "common items of a & b \n ";
printList(intersect);
return 0;
}
// This code is contributed by shivanisinghss2110
|
linear
|
linear
|
// C++ program to implement above approach
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* node)
{
while (node != NULL) {
cout << " " << node->data;
node = node->next;
}
}
void append(struct Node** head_ref, int new_data)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
vector<int> intersection(struct Node* tmp1, struct Node* tmp2,
int k)
{
vector<int> res(k);
unordered_set<int> set;
while (tmp1 != NULL) {
set.insert(tmp1->data);
tmp1 = tmp1->next;
}
int cnt = 0;
while (tmp2 != NULL) {
if (set.find(tmp2->data) != set.end()) {
res[cnt] = tmp2->data;
cnt++;
}
tmp2 = tmp2->next;
}
return res;
}
// Driver code
int main()
{
struct Node* ll = NULL;
struct Node* ll1 = NULL;
append(≪,7);
append(≪,6);
append(≪,5);
append(≪,4);
append(≪,3);
append(≪,2);
append(≪,1);
append(≪,0);
append(&ll1,7);
append(&ll1,6);
append(&ll1,5);
append(&ll1,4);
append(&ll1,3);
append(&ll1,12);
append(&ll1,0);
append(&ll1,9);
vector<int> arr= intersection(ll, ll1, 6);
for (int i :arr)
cout << i << "\n";
return 0;
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)
|
linear
|
linear
|
// C++ program for Quick Sort on Singly Linked List
#include <cstdio>
#include <iostream>
using namespace std;
/* a node of the singly linked list */
struct Node {
int data;
struct Node* next;
};
/* A utility function to insert a node at the beginning of
* linked list */
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 of 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 linked list */
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// Returns the last node of the list
struct Node* getTail(struct Node* cur)
{
while (cur != NULL && cur->next != NULL)
cur = cur->next;
return cur;
}
// Partitions the list taking the last element as the pivot
struct Node* partition(struct Node* head, struct Node* end,
struct Node** newHead,
struct Node** newEnd)
{
struct Node* pivot = end;
struct Node *prev = NULL, *cur = head, *tail = pivot;
// During partition, both the head and end of the list
// might change which is updated in the newHead and
// newEnd variables
while (cur != pivot) {
if (cur->data < pivot->data) {
// First node that has a value less than the
// pivot - becomes the new head
if ((*newHead) == NULL)
(*newHead) = cur;
prev = cur;
cur = cur->next;
}
else // If cur node is greater than pivot
{
// Move cur node to next of tail, and change
// tail
if (prev)
prev->next = cur->next;
struct Node* tmp = cur->next;
cur->next = NULL;
tail->next = cur;
tail = cur;
cur = tmp;
}
}
// If the pivot data is the smallest element in the
// current list, pivot becomes the head
if ((*newHead) == NULL)
(*newHead) = pivot;
// Update newEnd to the current last node
(*newEnd) = tail;
// Return the pivot node
return pivot;
}
// here the sorting happens exclusive of the end node
struct Node* quickSortRecur(struct Node* head,
struct Node* end)
{
// base condition
if (!head || head == end)
return head;
Node *newHead = NULL, *newEnd = NULL;
// Partition the list, newHead and newEnd will be
// updated by the partition function
struct Node* pivot
= partition(head, end, &newHead, &newEnd);
// If pivot is the smallest element - no need to recur
// for the left part.
if (newHead != pivot) {
// Set the node before the pivot node as NULL
struct Node* tmp = newHead;
while (tmp->next != pivot)
tmp = tmp->next;
tmp->next = NULL;
// Recur for the list before pivot
newHead = quickSortRecur(newHead, tmp);
// Change next of last node of the left half to
// pivot
tmp = getTail(newHead);
tmp->next = pivot;
}
// Recur for the list after the pivot element
pivot->next = quickSortRecur(pivot->next, newEnd);
return newHead;
}
// The main function for quick sort. This is a wrapper over
// recursive function quickSortRecur()
void quickSort(struct Node** headRef)
{
(*headRef)
= quickSortRecur(*headRef, getTail(*headRef));
return;
}
// Driver's code
int main()
{
struct Node* a = NULL;
push(&a, 5);
push(&a, 20);
push(&a, 4);
push(&a, 3);
push(&a, 30);
cout << "Linked List before sorting \n";
printList(a);
// Function call
quickSort(&a);
cout << "Linked List after sorting \n";
printList(a);
return 0;
}
|
linear
|
nlogn
|
// C++ program to segregate even and
// odd nodes in a Linked List
#include <bits/stdc++.h>
using namespace std;
/* a node of the singly linked list */
class Node
{
public:
int data;
Node *next;
};
void segregateEvenOdd(Node **head_ref)
{
Node *end = *head_ref;
Node *prev = NULL;
Node *curr = *head_ref;
/* Get pointer to the last node */
while (end->next != NULL)
end = end->next;
Node *new_end = end;
/* Consider all odd nodes before the first
even node and move then after end */
while (curr->data % 2 != 0 && curr != end)
{
new_end->next = curr;
curr = curr->next;
new_end->next->next = NULL;
new_end = new_end->next;
}
// 10->8->17->17->15
/* Do following steps only if
there is any even node */
if (curr->data%2 == 0)
{
/* Change the head pointer to
point to first even node */
*head_ref = curr;
/* now current points to
the first even node */
while (curr != end)
{
if ( (curr->data) % 2 == 0 )
{
prev = curr;
curr = curr->next;
}
else
{
/* break the link between
prev and current */
prev->next = curr->next;
/* Make next of curr as NULL */
curr->next = NULL;
/* Move curr to end */
new_end->next = curr;
/* make curr as new end of list */
new_end = curr;
/* Update current pointer to
next of the moved node */
curr = prev->next;
}
}
}
/* We must have prev set before executing
lines following this statement */
else prev = curr;
/* If there are more than 1 odd nodes
and end of original list is odd then
move this node to end to maintain
same order of odd numbers in modified list */
if (new_end != end && (end->data) % 2 != 0)
{
prev->next = end->next;
end->next = NULL;
new_end->next = end;
}
return;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning */
void push(Node** head_ref, int new_data)
{
/* allocate node */
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;
}
/* Function to print nodes in a given linked list */
void printList(Node *node)
{
while (node != NULL)
{
cout << node->data <<" ";
node = node->next;
}
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Let us create a sample linked list as following
0->2->4->6->8->10->11 */
push(&head, 11);
push(&head, 10);
push(&head, 8);
push(&head, 6);
push(&head, 4);
push(&head, 2);
push(&head, 0);
cout << "Original Linked list ";
printList(head);
segregateEvenOdd(&head);
cout << "\nModified Linked list ";
printList(head);
return 0;
}
// This code is contributed by rathbhupendra
|
constant
|
linear
|
// CPP program to segregate even and odd nodes in a
// Linked List
#include <bits/stdc++.h>
using namespace std;
/* a node of the singly linked list */
struct Node {
int data;
struct Node* next;
};
// Function to segregate even and odd nodes.
void segregateEvenOdd(struct Node** head_ref)
{
// Starting node of list having even values.
Node* evenStart = NULL;
// Ending node of even values list.
Node* evenEnd = NULL;
// Starting node of odd values list.
Node* oddStart = NULL;
// Ending node of odd values list.
Node* oddEnd = NULL;
// Node to traverse the list.
Node* currNode = *head_ref;
while (currNode != NULL) {
int val = currNode->data;
// If current value is even, add it to even values
// list.
if (val % 2 == 0) {
if (evenStart == NULL) {
evenStart = currNode;
evenEnd = evenStart;
}
else {
evenEnd->next = currNode;
evenEnd = evenEnd->next;
}
}
// If current value is odd, add it to odd values
// list.
else {
if (oddStart == NULL) {
oddStart = currNode;
oddEnd = oddStart;
}
else {
oddEnd->next = currNode;
oddEnd = oddEnd->next;
}
}
// Move head pointer one step in forward direction
currNode = currNode->next;
}
// If either odd list or even list is empty, no change
// is required as all elements are either even or odd.
if (oddStart == NULL || evenStart == NULL)
return;
// Add odd list after even list.
evenEnd->next = oddStart;
oddEnd->next = NULL;
// Modify head pointer to starting of even list.
*head_ref = evenStart;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning */
void push(Node** head_ref, int new_data)
{
/* allocate node */
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;
}
/* Function to print nodes in a given linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Let us create a sample linked list as following
0->1->4->6->9->10->11 */
push(&head, 11);
push(&head, 10);
push(&head, 9);
push(&head, 6);
push(&head, 4);
push(&head, 1);
push(&head, 0);
cout << "Original Linked list" << endl;
printList(head);
segregateEvenOdd(&head);
cout << endl << "Modified Linked list " << endl;
printList(head);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
constant
|
linear
|
// Iterative C++ program to reverse a linked list
#include <bits/stdc++.h>
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;
}
|
constant
|
linear
|
// Recursive C++ program to reverse
// a linked list
#include <bits/stdc++.h>
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; }
Node* reverse(Node* head)
{
if (head == NULL || head->next == NULL)
return head;
/* reverse the rest list and put
the first element at the end */
Node* rest = reverse(head->next);
head->next->next = head;
/* tricky step -- see the diagram */
head->next = NULL;
/* fix the head pointer */
return rest;
}
/* 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.head = ll.reverse(ll.head);
cout << "\nReversed linked list \n";
ll.print();
return 0;
}
|
linear
|
linear
|
// A simple and tail recursive C++ program to reverse
// a linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void reverseUtil(Node* curr, Node* prev, Node** head);
// This function mainly calls reverseUtil()
// with prev as NULL
void reverse(Node** head)
{
if (!head)
return;
reverseUtil(*head, NULL, head);
}
// A simple and tail-recursive function to reverse
// a linked list. prev is passed as NULL initially.
void reverseUtil(Node* curr, Node* prev, Node** head)
{
/* If last node mark it head*/
if (!curr->next) {
*head = curr;
/* Update next to prev node */
curr->next = prev;
return;
}
/* Save curr->next node for recursive call */
Node* next = curr->next;
/* and update next ..*/
curr->next = prev;
reverseUtil(next, curr, head);
}
// A utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// A utility function to print a linked list
void printlist(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
// Driver code
int main()
{
Node* head1 = newNode(1);
head1->next = newNode(2);
head1->next->next = newNode(3);
head1->next->next->next = newNode(4);
head1->next->next->next->next = newNode(5);
head1->next->next->next->next->next = newNode(6);
head1->next->next->next->next->next->next = newNode(7);
head1->next->next->next->next->next->next->next
= newNode(8);
cout << "Given linked list\n";
printlist(head1);
reverse(&head1);
cout << "Reversed linked list\n";
printlist(head1);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
linear
|
linear
|
// C++ program for above approach
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Create a class Node to enter values and address in the
// list
class Node {
public:
int data;
Node* next;
};
// Function to reverse the linked list
void reverseLL(Node** head)
{
// Create a stack "s" of Node type
stack<Node*> s;
Node* temp = *head;
while (temp->next != NULL) {
// Push all the nodes in to stack
s.push(temp);
temp = temp->next;
}
*head = temp;
while (!s.empty()) {
// Store the top value of stack in list
temp->next = s.top();
// Pop the value from stack
s.pop();
// update the next pointer in the list
temp = temp->next;
}
temp->next = NULL;
}
// Function to Display the elements in List
void printlist(Node* temp)
{
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
// Program to insert back of the linked list
void insert_back(Node** head, int value)
{
// we have used insertion at back method to enter values
// in the list.(eg: head->1->2->3->4->Null)
Node* temp = new Node();
temp->data = value;
temp->next = NULL;
// If *head equals to NULL
if (*head == NULL) {
*head = temp;
return;
}
else {
Node* last_node = *head;
while (last_node->next != NULL)
last_node = last_node->next;
last_node->next = temp;
return;
}
}
// Driver Code
int main()
{
Node* head = NULL;
insert_back(&head, 1);
insert_back(&head, 2);
insert_back(&head, 3);
insert_back(&head, 4);
cout << "Given linked list\n";
printlist(head);
reverseLL(&head);
cout << "\nReversed linked list\n";
printlist(head);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
linear
|
linear
|
// C++ program to delete a given key from
// linked list.
#include <bits/stdc++.h>
using namespace std;
// Structure for a node
class Node {
public:
int data;
Node* next;
};
// Function to insert a node at the
// beginning of a Circular linked list
void push(Node** head_ref, int data)
{
// Create a new node and make head
// as next of it.
Node* ptr1 = new Node();
ptr1->data = data;
ptr1->next = *head_ref;
// If linked list is not NULL then
// set the next of last node
if (*head_ref != NULL) {
// Find the node before head and
// update next of it.
Node* temp = *head_ref;
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
// For the first node
ptr1->next = ptr1;
*head_ref = ptr1;
}
// Function to print nodes in a given
// circular linked list
void printList(Node* head)
{
Node* temp = head;
if (head != NULL) {
do {
cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
}
cout << endl;
}
// Function to delete a given node
// from the list
void deleteNode(Node** head, int key)
{
// If linked list is empty
if (*head == NULL)
return;
// If the list contains only a
// single node
if ((*head)->data == key && (*head)->next == *head) {
free(*head);
*head = NULL;
return;
}
Node *last = *head, *d;
// If head is to be deleted
if ((*head)->data == key) {
// Find the last node of the list
while (last->next != *head)
last = last->next;
// Point last node to the next of
// head i.e. the second node
// of the list
last->next = (*head)->next;
free(*head);
*head = last->next;
return;
}
// Either the node to be deleted is
// not found or the end of list
// is not reached
while (last->next != *head && last->next->data != key) {
last = last->next;
}
// If node to be deleted was found
if (last->next->data == key) {
d = last->next;
last->next = d->next;
free(d);
}
else
cout << "no such keyfound";
}
// Driver code
int main()
{
// Initialize lists as empty
Node* head = NULL;
// Created linked list will be
// 2->5->7->8->10
push(&head, 2);
push(&head, 5);
push(&head, 7);
push(&head, 8);
push(&head, 10);
cout << "List Before Deletion: ";
printList(head);
deleteNode(&head, 7);
cout << "List After Deletion: ";
printList(head);
return 0;
}
|
constant
|
linear
|
// C++ program to check if linked list is circular
#include<bits/stdc++.h>
using namespace std;
/* Link list Node */
struct Node
{
int data;
struct Node* next;
};
/* This function returns true if given linked
list is circular, else false. */
bool isCircular(struct Node *head)
{
// An empty linked list is circular
if (head == NULL)
return true;
// Next of head
struct Node *node = head->next;
// This loop would stop in both cases (1) If
// Circular (2) Not circular
while (node != NULL && node != head)
node = node->next;
// If loop stopped because of circular
// condition
return (node == head);
}
// Utility function to create a new node.
Node *newNode(int data)
{
struct Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
// Driver's code
int main()
{
/* Start with the empty list */
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
isCircular(head)? cout << "Yes\n" :
cout << "No\n" ;
// Making linked list circular
head->next->next->next->next = head;
isCircular(head)? cout << "Yes\n" :
cout << "No\n" ;
return 0;
}
|
constant
|
linear
|
// C++ Program to convert a Binary Tree
// to a Circular Doubly Linked List
#include <iostream>
using namespace std;
// To represents a node of a Binary Tree
struct Node {
struct Node *left, *right;
int data;
};
// A function that appends rightList at the end
// of leftList.
Node* concatenate(Node* leftList, Node* rightList)
{
// If either of the list is empty
// then return the other list
if (leftList == NULL)
return rightList;
if (rightList == NULL)
return leftList;
// Store the last Node of left List
Node* leftLast = leftList->left;
// Store the last Node of right List
Node* rightLast = rightList->left;
// Connect the last node of Left List
// with the first Node of the right List
leftLast->right = rightList;
rightList->left = leftLast;
// Left of first node points to
// the last node in the list
leftList->left = rightLast;
// Right of last node refers to the first
// node of the List
rightLast->right = leftList;
return leftList;
}
// Function converts a tree to a circular Linked List
// and then returns the head of the Linked List
Node* bTreeToCList(Node* root)
{
if (root == NULL)
return NULL;
// Recursively convert left and right subtrees
Node* left = bTreeToCList(root->left);
Node* right = bTreeToCList(root->right);
// Make a circular linked list of single node
// (or root). To do so, make the right and
// left pointers of this node point to itself
root->left = root->right = root;
// Step 1 (concatenate the left list with the list
// with single node, i.e., current node)
// Step 2 (concatenate the returned list with the
// right List)
return concatenate(concatenate(left, root), right);
}
// Display Circular Link List
void displayCList(Node* head)
{
cout << "Circular Linked List is :\n";
Node* itr = head;
do {
cout << itr->data << " ";
itr = itr->right;
} while (head != itr);
cout << "\n";
}
// Create a new Node and return its address
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver Program to test above function
int main()
{
Node* root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
Node* head = bTreeToCList(root);
displayCList(head);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
logn
|
linear
|
// A C++ program for in-place conversion of Binary Tree to
// CDLL
#include <iostream>
using namespace std;
/* A binary tree node has - data , left and right pointers
*/
struct Node {
int data;
Node* left;
Node* right;
};
// A utility function that converts given binary tree to
// a doubly linked list
// root --> the root of the binary tree
// head --> head of the created doubly linked list
Node* BTree2DoublyLinkedList(Node* root, Node** head)
{
// Base case
if (root == NULL)
return root;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all
// recursive calls
static Node* prev = NULL;
// Recursively convert left subtree
BTree2DoublyLinkedList(root->left, head);
// Now convert this node
if (prev == NULL)
*head = root;
else {
root->left = prev;
prev->right = root;
}
prev = root;
// Finally convert right subtree
BTree2DoublyLinkedList(root->right, head);
return prev;
}
// A simple recursive function to convert a given Binary
// tree to Circular Doubly Linked List using a utility
// function root --> Root of Binary Tree tail --> Pointer to
// tail node of created circular doubly linked list
Node* BTree2CircularDoublyLinkedList(Node* root)
{
Node* head = NULL;
Node* tail = BTree2DoublyLinkedList(root, &head);
// make the changes to convert a DLL to CDLL
tail->right = head;
head->left = tail;
// return the head of the created CDLL
return head;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
/* Function to print nodes in a given circular doubly linked
* list */
void printList(Node* head)
{
if (head == NULL)
return;
Node* ptr = head;
do {
cout << ptr->data << " ";
ptr = ptr->right;
} while (ptr != head);
}
/* Driver program to test above functions*/
int main()
{
// Let us create the tree shown in above diagram
Node* root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
// Convert to DLL
Node* head = BTree2CircularDoublyLinkedList(root);
// Print the converted list
printList(head);
return 0;
}
// This code was contributed by Abhijeet
// Kumar(abhijeet19403)
|
logn
|
linear
|
// C++ program to count number of nodes in a circular
// linked list.
#include <bits/stdc++.h>
using namespace std;
/*structure for a node*/
struct Node {
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
/* Function to insert a node at the beginning
of a Circular linked list */
struct Node* push(struct Node* last, int data)
{
if (last == NULL) {
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
temp->data = data;
last = temp;
// Note : list was empty. We link single node
// to itself.
temp->next = last;
return last;
}
// Creating a node dynamically.
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
temp->data = data;
// Adjusting the links.
temp->next = last->next;
last->next = temp;
return last;
}
/* Function to count nodes in a given Circular
linked list */
int countNodes(Node* head)
{
Node* temp = head;
int result = 0;
if (head != NULL) {
do {
temp = temp->next;
result++;
} while (temp != head);
}
return result;
}
/* Driver program to test above functions */
int main()
{
/* Initialize lists as empty */
Node* head = NULL;
head = push(head, 12);
head = push(head, 56);
head = push(head, 2);
head = push(head, 11);
cout << countNodes(head);
return 0;
}
// This code is contributed by anushikaseth
|
constant
|
linear
|
// C++ program to delete a given key from
// linked list.
#include <bits/stdc++.h>
using namespace std;
// Structure for a node
class Node {
public:
int data;
Node* next;
};
// Function to insert a node at the
// beginning of a Circular linked list
void push(Node** head_ref, int data)
{
// Create a new node and make head
// as next of it.
Node* ptr1 = new Node();
ptr1->data = data;
ptr1->next = *head_ref;
// If linked list is not NULL then
// set the next of last node
if (*head_ref != NULL) {
// Find the node before head and
// update next of it.
Node* temp = *head_ref;
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
// For the first node
ptr1->next = ptr1;
*head_ref = ptr1;
}
// Function to print nodes in a given
// circular linked list
void printList(Node* head)
{
Node* temp = head;
if (head != NULL) {
do {
cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
}
cout << endl;
}
// Function to delete a given node
// from the list
void deleteNode(Node** head, int key)
{
// If linked list is empty
if (*head == NULL)
return;
// If the list contains only a
// single node
if ((*head)->data == key && (*head)->next == *head) {
free(*head);
*head = NULL;
return;
}
Node *last = *head, *d;
// If head is to be deleted
if ((*head)->data == key) {
// Find the last node of the list
while (last->next != *head)
last = last->next;
// Point last node to the next of
// head i.e. the second node
// of the list
last->next = (*head)->next;
free(*head);
*head = last->next;
return;
}
// Either the node to be deleted is
// not found or the end of list
// is not reached
while (last->next != *head && last->next->data != key) {
last = last->next;
}
// If node to be deleted was found
if (last->next->data == key) {
d = last->next;
last->next = d->next;
free(d);
}
else
cout << "no such keyfound";
}
// Driver code
int main()
{
// Initialize lists as empty
Node* head = NULL;
// Created linked list will be
// 2->5->7->8->10
push(&head, 2);
push(&head, 5);
push(&head, 7);
push(&head, 8);
push(&head, 10);
cout << "List Before Deletion: ";
printList(head);
deleteNode(&head, 7);
cout << "List After Deletion: ";
printList(head);
return 0;
}
|
constant
|
linear
|
// C++ implementation of De-queue using circular
// array
#include <iostream>
using namespace std;
// Maximum size of array or Dequeue
#define MAX 100
// A structure to represent a Deque
class Deque {
int arr[MAX];
int front;
int rear;
int size;
public:
Deque(int size)
{
front = -1;
rear = 0;
this->size = size;
}
// Operations on Deque:
void insertfront(int key);
void insertrear(int key);
void deletefront();
void deleterear();
bool isFull();
bool isEmpty();
int getFront();
int getRear();
};
// Checks whether Deque is full or not.
bool Deque::isFull()
{
return ((front == 0 && rear == size - 1)
|| front == rear + 1);
}
// Checks whether Deque is empty or not.
bool Deque::isEmpty() { return (front == -1); }
// Inserts an element at front
void Deque::insertfront(int key)
{
// check whether Deque if full or not
if (isFull()) {
cout << "Overflow\n" << endl;
return;
}
// If queue is initially empty
if (front == -1) {
front = 0;
rear = 0;
}
// front is at first position of queue
else if (front == 0)
front = size - 1;
else // decrement front end by '1'
front = front - 1;
// insert current element into Deque
arr[front] = key;
}
// function to inset element at rear end
// of Deque.
void Deque ::insertrear(int key)
{
if (isFull()) {
cout << " Overflow\n " << endl;
return;
}
// If queue is initially empty
if (front == -1) {
front = 0;
rear = 0;
}
// rear is at last position of queue
else if (rear == size - 1)
rear = 0;
// increment rear end by '1'
else
rear = rear + 1;
// insert current element into Deque
arr[rear] = key;
}
// Deletes element at front end of Deque
void Deque ::deletefront()
{
// check whether Deque is empty or not
if (isEmpty()) {
cout << "Queue Underflow\n" << endl;
return;
}
// Deque has only one element
if (front == rear) {
front = -1;
rear = -1;
}
else
// back to initial position
if (front == size - 1)
front = 0;
else // increment front by '1' to remove current
// front value from Deque
front = front + 1;
}
// Delete element at rear end of Deque
void Deque::deleterear()
{
if (isEmpty()) {
cout << " Underflow\n" << endl;
return;
}
// Deque has only one element
if (front == rear) {
front = -1;
rear = -1;
}
else if (rear == 0)
rear = size - 1;
else
rear = rear - 1;
}
// Returns front element of Deque
int Deque::getFront()
{
// check whether Deque is empty or not
if (isEmpty()) {
cout << " Underflow\n" << endl;
return -1;
}
return arr[front];
}
// function return rear element of Deque
int Deque::getRear()
{
// check whether Deque is empty or not
if (isEmpty() || rear < 0) {
cout << " Underflow\n" << endl;
return -1;
}
return arr[rear];
}
// Driver code
int main()
{
Deque dq(5);
// Function calls
cout << "Insert element at rear end : 5 \n";
dq.insertrear(5);
cout << "insert element at rear end : 10 \n";
dq.insertrear(10);
cout << "get rear element "
<< " " << dq.getRear() << endl;
dq.deleterear();
cout << "After delete rear element new rear"
<< " become " << dq.getRear() << endl;
cout << "inserting element at front end \n";
dq.insertfront(15);
cout << "get front element "
<< " " << dq.getFront() << endl;
dq.deletefront();
cout << "After delete front element new "
<< "front become " << dq.getFront() << endl;
return 0;
}
|
linear
|
linear
|
// CPP program to exchange first and
// last node in circular linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
struct Node* addToEmpty(struct Node* head, int data)
{
// This function is only for empty list
if (head != NULL)
return head;
// Creating a node dynamically.
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
temp->data = data;
head = temp;
// Creating the link.
head->next = head;
return head;
}
struct Node* addBegin(struct Node* head, int data)
{
if (head == NULL)
return addToEmpty(head, data);
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = head->next;
head->next = temp;
return head;
}
/* function for traversing the list */
void traverse(struct Node* head)
{
struct Node* p;
// If list is empty, return.
if (head == NULL) {
cout << "List is empty." << endl;
return;
}
// Pointing to first Node of the list.
p = head;
// Traversing the list.
do {
cout << p->data << " ";
p = p->next;
} while (p != head);
}
/* Function to exchange first and last node*/
struct Node* exchangeNodes(struct Node* head)
{
// If list is of length less than 2
if (head == NULL || head->next == NULL) {
return head;
}
Node* tail = head;
// Find pointer to the last node
while (tail->next != head) {
tail = tail->next;
}
/* Exchange first and last nodes using
head and p */
// temporary variable to store
// head data
int temp = tail->data;
tail->data = head->data;
head->data = temp;
return head;
}
// Driven Program
int main()
{
int i;
struct Node* head = NULL;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
cout << "List Before: ";
traverse(head);
cout << endl;
cout << "List After: ";
head = exchangeNodes(head);
traverse(head);
return 0;
}
|
constant
|
linear
|
// A complete working C++ program to
// demonstrate all insertion methods
#include <bits/stdc++.h>
using namespace std;
// A linked list node
class Node {
public:
int data;
Node* next;
Node* prev;
};
/* Given a reference (pointer to pointer)
to the head of a list
and an int, inserts a new node on the
front of the list. */
void push(Node** head_ref, int new_data)
{
/* 1. allocate node */
Node* new_node = new Node();
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head
and previous as NULL */
new_node->next = (*head_ref);
new_node->prev = NULL;
/* 4. change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* 5. move the head to point to the new node */
(*head_ref) = new_node;
}
/* Given a node as prev_node, insert
a new node after the given node */
void insertAfter(Node* prev_node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_node == NULL) {
cout << "the given previous node cannot be NULL";
return;
}
/* 2. allocate new node */
Node* new_node = new Node();
/* 3. put in the data */
new_node->data = new_data;
/* 4. Make next of new node as next of prev_node */
new_node->next = prev_node->next;
/* 5. Make the next of prev_node as new_node */
prev_node->next = new_node;
/* 6. Make prev_node as previous of new_node */
new_node->prev = prev_node;
/* 7. Change previous of new_node's next node */
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
/* Given a reference (pointer to pointer) to the head
of a DLL and an int, appends a new node at the end */
void append(Node** head_ref, int new_data)
{
/* 1. allocate node */
Node* new_node = new Node();
Node* last = *head_ref; /* used in step 5*/
/* 2. put in the data */
new_node->data = new_data;
/* 3. This new node is going to be the last node, so
make next of it as NULL*/
new_node->next = NULL;
/* 4. If the Linked List is empty, then make the new
node as head */
if (*head_ref == NULL) {
new_node->prev = NULL;
*head_ref = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last->next != NULL)
last = last->next;
/* 6. Change the next of last node */
last->next = new_node;
/* 7. Make last node as previous of new node */
new_node->prev = last;
return;
}
// This function prints contents of
// linked list starting from the given node
void printList(Node* node)
{
Node* last;
cout << "\nTraversal in forward direction \n";
while (node != NULL) {
cout << " " << node->data << " ";
last = node;
node = node->next;
}
cout << "\nTraversal in reverse direction \n";
while (last != NULL) {
cout << " " << last->data << " ";
last = last->prev;
}
}
// Driver code
int main()
{
/* Start with the empty list */
Node* head = NULL;
// Insert 6. So linked list becomes 6->NULL
append(&head, 6);
// Insert 7 at the beginning. So
// linked list becomes 7->6->NULL
push(&head, 7);
// Insert 1 at the beginning. So
// linked list becomes 1->7->6->NULL
push(&head, 1);
// Insert 4 at the end. So linked
// list becomes 1->7->6->4->NULL
append(&head, 4);
// Insert 8, after 7. So linked
// list becomes 1->7->8->6->4->NULL
insertAfter(head->next, 8);
cout << "Created DLL is: ";
printList(head);
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
class node {
public:
node* prev;
int data;
node* next;
node(int value)
{ // A constructor is called here
prev = NULL; // By default previous pointer is
// pointed to NULL
data = value; // value is assigned to the data
next = NULL; // By default next pointer is pointed
// to NULL
}
};
void insert_at_head(node*& head, int value)
{
node* n = new node(value);
n->next = head;
if (head != NULL) {
head->prev = n;
}
head = n;
}
void insert_at_tail(node*& head, int value)
{
if (head == NULL) {
insert_at_head(head, value);
return;
}
node* n = new node(value);
node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = n;
n->prev = temp;
}
void display(node* head)
{
node* temp = head;
while (temp != NULL) {
cout << temp->data << " --> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
// Driver code
int main()
{
node* head
= NULL; // declaring an empty doubly linked list
// Function call
insert_at_tail(head, 1);
insert_at_tail(head, 2);
insert_at_tail(head, 3);
insert_at_tail(head, 4);
insert_at_tail(head, 5);
cout << "After insertion at tail: ";
display(head);
cout << "After insertion at head: ";
insert_at_head(head, 0);
display(head);
return 0;
}
|
constant
|
linear
|
// C++ program to delete a node from
// Doubly Linked List
#include <bits/stdc++.h>
using namespace std;
/* a node of the doubly linked list */
class Node
{
public:
int data;
Node* next;
Node* prev;
};
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(Node** head_ref, Node* del)
{
/* base case */
if (*head_ref == NULL || del == NULL)
return;
/* If node to be deleted is head node */
if (*head_ref == del)
*head_ref = del->next;
/* Change next only if node to be
deleted is NOT the last node */
if (del->next != NULL)
del->next->prev = del->prev;
/* Change prev only if node to be
deleted is NOT the first node */
if (del->prev != NULL)
del->prev->next = del->next;
/* Finally, free the memory occupied by del*/
free(del);
return;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the
beginning of the Doubly Linked List */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = new_data;
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly linked list
This function is same as printList() of singly linked list */
void printList(Node* node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Let us create the doubly linked list 10<->8<->4<->2 */
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
cout << "Original Linked list ";
printList(head);
/* delete nodes from the doubly linked list */
deleteNode(&head, head); /*delete first node*/
deleteNode(&head, head->next); /*delete middle node*/
deleteNode(&head, head->next); /*delete last node*/
/* Modified linked list will be NULL<-8->NULL */
cout << "\nModified Linked list ";
printList(head);
return 0;
}
// This code is contributed by rathbhupendra
|
constant
|
constant
|
/* C++ program to reverse a doubly linked list */
#include <bits/stdc++.h>
using namespace std;
/* Node of the doubly linked list */
class Node {
public:
int data;
Node* next;
Node* prev;
};
/* Function to reverse a Doubly Linked List */
void reverse(Node** head_ref)
{
Node* temp = NULL;
Node* current = *head_ref;
/* swap next and prev for all nodes of
doubly linked list */
while (current != NULL) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
/* Before changing the head, check for the cases like
empty list and list with only one node */
if (temp != NULL)
*head_ref = temp->prev;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the
beginning of the Doubly Linked List */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = new_data;
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly linked list
This function is same as printList() of singly linked list
*/
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
// Driver's code
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Let us create a sorted linked list to test the
functions Created linked list will be 10->8->4->2 */
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
cout << "Original Linked list" << endl;
printList(head);
// Function call
reverse(&head);
cout << "\nReversed Linked list" << endl;
printList(head);
return 0;
}
// This code is contributed by rathbhupendra
|
constant
|
linear
|
// C++ program to reverse a doubly linked list
#include <bits/stdc++.h>
using namespace std;
struct LinkedList {
struct Node {
int data;
Node *next, *prev;
Node(int d)
{
data = d;
next = prev = NULL;
}
};
Node* head = NULL;
/* Function to reverse a Doubly Linked List using Stacks
*/
void reverse()
{
stack<int> st;
Node* temp = head;
while (temp != NULL) {
st.push(temp->data);
temp = temp->next;
}
// added all the elements sequence wise in the
// st
temp = head;
while (temp != NULL) {
temp->data = st.top();
st.pop();
temp = temp->next;
}
// popped all the elements and the added in the
// linked list,
// which are in the reversed order->
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the
* Doubly Linked List */
void Push(int new_data)
{
/* allocate node */
Node* new_node = new Node(new_data);
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list of the new node */
new_node->next = head;
/* change prev of head node to new node */
if (head != NULL) {
head->prev = new_node;
}
/* move the head to point to the new node */
head = new_node;
}
/* Function to print nodes in a given doubly linked list
This function is same as printList() of singly linked
list */
void printList(Node* node)
{
while (node) {
cout << node->data << " ";
node = node->next;
}
}
};
// Driver Code
int main()
{
LinkedList list;
/* Let us create a sorted linked list to test the
functions Created linked list will be 10->8->4->2
*/
list.Push(2);
list.Push(4);
list.Push(8);
list.Push(10);
cout << "Original linked list " << endl;
list.printList(list.head);
list.reverse();
cout << endl;
cout << "The reversed Linked List is " << endl;
list.printList(list.head);
}
// This code is contributed by Pratham76
|
linear
|
linear
|
// A C++ program to swap Kth node from beginning with kth
// node from end
#include <bits/stdc++.h>
using namespace std;
// A Linked List node
typedef struct Node {
int data;
struct Node* next;
} Node;
// Utility function to insert a node at the beginning
void push(Node** head_ref, int new_data)
{
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Utility function for displaying linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
/* Utility function for calculating
length of linked list */
int countNodes(struct Node* s)
{
int count = 0;
while (s != NULL) {
count++;
s = s->next;
}
return count;
}
// Utility function for calculating length of linked list
void swapKth(struct Node** head_ref, int k)
{
// Count nodes in linked list
int n = countNodes(*head_ref);
// Check if k is valid
if (n < k)
return;
// If x (kth node from start) and y(kth node from end)
// are same
if (2 * k - 1 == n)
return;
// Find the kth node from the beginning of the linked
// list. We also find previous of kth node because we
// need to update next pointer of the previous.
Node* x = *head_ref;
Node* x_prev = NULL;
for (int i = 1; i < k; i++) {
x_prev = x;
x = x->next;
}
// Similarly, find the kth node from end and its
// previous. kth node from end is (n-k+1)th node from
// beginning
Node* y = *head_ref;
Node* y_prev = NULL;
for (int i = 1; i < n - k + 1; i++) {
y_prev = y;
y = y->next;
}
// If x_prev exists, then new next of it will be y.
// Consider the case when y->next is x, in this case,
// x_prev and y are same. So the statement "x_prev->next
// = y" creates a self loop. This self loop will be
// broken when we change y->next.
if (x_prev)
x_prev->next = y;
// Same thing applies to y_prev
if (y_prev)
y_prev->next = x;
// Swap next pointers of x and y. These statements also
// break self loop if x->next is y or y->next is x
Node* temp = x->next;
x->next = y->next;
y->next = temp;
// Change head pointers when k is 1 or n
if (k == 1)
*head_ref = y;
if (k == n)
*head_ref = x;
}
// Driver code
int main()
{
// Let us create the following linked list for testing
// 1->2->3->4->5->6->7->8
struct Node* head = NULL;
for (int i = 8; i >= 1; i--)
push(&head, i);
cout << "Original Linked List: ";
printList(head);
for (int k = 1; k < 9; k++) {
// Function call
swapKth(&head, k);
cout << "\nModified List for k = " << k << endl;
printList(head);
}
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
constant
|
linear
|
// C++ program for merge sort on doubly linked list
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next, *prev;
};
Node *split(Node *head);
// Function to merge two linked lists
Node *merge(Node *first, Node *second)
{
// If first linked list is empty
if (!first)
return second;
// If second linked list is empty
if (!second)
return first;
// Pick the smaller value
if (first->data < second->data)
{
first->next = merge(first->next,second);
first->next->prev = first;
first->prev = NULL;
return first;
}
else
{
second->next = merge(first,second->next);
second->next->prev = second;
second->prev = NULL;
return second;
}
}
// Function to do merge sort
Node *mergeSort(Node *head)
{
if (!head || !head->next)
return head;
Node *second = split(head);
// Recur for left and right halves
head = mergeSort(head);
second = mergeSort(second);
// Merge the two sorted halves
return merge(head,second);
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(Node **head, int data)
{
Node *temp = new Node();
temp->data = data;
temp->next = temp->prev = NULL;
if (!(*head))
(*head) = temp;
else
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// A utility function to print a doubly linked list in
// both forward and backward directions
void print(Node *head)
{
Node *temp = head;
cout<<"Forward Traversal using next pointer\n";
while (head)
{
cout << head->data << " ";
temp = head;
head = head->next;
}
cout << "\nBackward Traversal using prev pointer\n";
while (temp)
{
cout << temp->data << " ";
temp = temp->prev;
}
}
// Utility function to swap two integers
void swap(int *A, int *B)
{
int temp = *A;
*A = *B;
*B = temp;
}
// Split a doubly linked list (DLL) into 2 DLLs of
// half sizes
Node *split(Node *head)
{
Node *fast = head,*slow = head;
while (fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
}
Node *temp = slow->next;
slow->next = NULL;
return temp;
}
// Driver program
int main(void)
{
Node *head = NULL;
insert(&head, 5);
insert(&head, 20);
insert(&head, 4);
insert(&head, 3);
insert(&head, 30);
insert(&head, 10);
head = mergeSort(head);
cout << "Linked List after sorting\n";
print(head);
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
nlogn
|
// C++ program to create a doubly linked list out
// of given a ternary tree.
#include <bits/stdc++.h>
using namespace std;
/* A ternary tree */
struct Node
{
int data;
struct Node *left, *middle, *right;
};
/* Helper function that allocates a new node with the
given data and assign NULL to left, middle and right
pointers.*/
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->middle = node->right = NULL;
return node;
}
/* Utility function that constructs doubly linked list
by inserting current node at the end of the doubly
linked list by using a tail pointer */
void push(Node** tail_ref, Node* node)
{
// initialize tail pointer
if (*tail_ref == NULL)
{
*tail_ref = node;
// set left, middle and right child to point
// to NULL
node->left = node->middle = node->right = NULL;
return;
}
// insert node in the end using tail pointer
(*tail_ref)->right = node;
// set prev of node
node->left = (*tail_ref);
// set middle and right child to point to NULL
node->right = node->middle = NULL;
// now tail pointer will point to inserted node
(*tail_ref) = node;
}
/* Create a doubly linked list out of given a ternary tree.
by traversing the tree in preorder fashion. */
void TernaryTreeToList(Node* root, Node** head_ref)
{
// Base case
if (root == NULL)
return;
//create a static tail pointer
static Node* tail = NULL;
// store left, middle and right nodes
// for future calls.
Node* left = root->left;
Node* middle = root->middle;
Node* right = root->right;
// set head of the doubly linked list
// head will be root of the ternary tree
if (*head_ref == NULL)
*head_ref = root;
// push current node in the end of DLL
push(&tail, root);
//recurse for left, middle and right child
TernaryTreeToList(left, head_ref);
TernaryTreeToList(middle, head_ref);
TernaryTreeToList(right, head_ref);
}
// Utility function for printing double linked list.
void printList(Node* head)
{
printf("Created Double Linked list is:\n");
while (head)
{
printf("%d ", head->data);
head = head->right;
}
}
// Driver program to test above functions
int main()
{
// Constructing ternary tree as shown in above figure
Node* root = newNode(30);
root->left = newNode(5);
root->middle = newNode(11);
root->right = newNode(63);
root->left->left = newNode(1);
root->left->middle = newNode(4);
root->left->right = newNode(8);
root->middle->left = newNode(6);
root->middle->middle = newNode(7);
root->middle->right = newNode(15);
root->right->left = newNode(31);
root->right->middle = newNode(55);
root->right->right = newNode(65);
Node* head = NULL;
TernaryTreeToList(root, &head);
printList(head);
return 0;
}
|
linear
|
linear
|
// C++ program to find a pair with given sum x.
#include<bits/stdc++.h>
using namespace std;
// structure of node of doubly linked list
struct Node
{
int data;
struct Node *next, *prev;
};
// Function to find pair whose sum equal to given value x.
void pairSum(struct Node *head, int x)
{
// Set two pointers, first to the beginning of DLL
// and second to the end of DLL.
struct Node *first = head;
struct Node *second = head;
while (second->next != NULL)
second = second->next;
// To track if we find a pair or not
bool found = false;
// The loop terminates when two pointers
// cross each other (second->next
// == first), or they become same (first == second)
while (first != second && second->next != first)
{
// pair found
if ((first->data + second->data) == x)
{
found = true;
cout << "(" << first->data<< ", "
<< second->data << ")" << endl;
// move first in forward direction
first = first->next;
// move second in backward direction
second = second->prev;
}
else
{
if ((first->data + second->data) < x)
first = first->next;
else
second = second->prev;
}
}
// if pair is not present
if (found == false)
cout << "No pair found";
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node **head, int data)
{
struct Node *temp = new Node;
temp->data = data;
temp->next = temp->prev = NULL;
if (!(*head))
(*head) = temp;
else
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// Driver program
int main()
{
struct Node *head = NULL;
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 7;
pairSum(head, x);
return 0;
}
|
constant
|
linear
|
// C++ implementation to insert value in sorted way
// in a sorted doubly linked list
#include <bits/stdc++.h>
using namespace std;
// Node of a doubly linked list
struct Node {
int data;
struct Node* prev, *next;
};
// function to create and return a new node
// of a doubly linked list
struct Node* getNode(int data)
{
// allocate node
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
// put in the data
newNode->data = data;
newNode->prev = newNode->next = NULL;
return newNode;
}
// function to insert a new node in sorted way in
// a sorted doubly linked list
void sortedInsert(struct Node** head_ref, struct Node* newNode)
{
struct Node* current;
// if list is empty
if (*head_ref == NULL)
*head_ref = newNode;
// if the node is to be inserted at the beginning
// of the doubly linked list
else if ((*head_ref)->data >= newNode->data) {
newNode->next = *head_ref;
newNode->next->prev = newNode;
*head_ref = newNode;
}
else {
current = *head_ref;
// locate the node after which the new node
// is to be inserted
while (current->next != NULL &&
current->next->data < newNode->data)
current = current->next;
/* Make the appropriate links */
newNode->next = current->next;
// if the new node is not inserted
// at the end of the list
if (current->next != NULL)
newNode->next->prev = newNode;
current->next = newNode;
newNode->prev = current;
}
}
// function to print the doubly linked list
void printList(struct Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
/* start with the empty doubly linked list */
struct Node* head = NULL;
// insert the following nodes in sorted way
struct Node* new_node = getNode(8);
sortedInsert(&head, new_node);
new_node = getNode(5);
sortedInsert(&head, new_node);
new_node = getNode(3);
sortedInsert(&head, new_node);
new_node = getNode(10);
sortedInsert(&head, new_node);
new_node = getNode(12);
sortedInsert(&head, new_node);
new_node = getNode(9);
sortedInsert(&head, new_node);
cout << "Created Doubly Linked Listn";
printList(head);
return 0;
}
|
linear
|
linear
|
// C++ implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;
// structure of node of doubly linked list
struct Node {
int data;
struct Node* next, *prev;
};
// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node* head, int x)
{
struct Node* ptr1, *ptr2, *ptr3;
int count = 0;
// generate all possible triplets
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next)
for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next)
for (ptr3 = ptr2->next; ptr3 != NULL; ptr3 = ptr3->next)
// if elements in the current triplet sum up to 'x'
if ((ptr1->data + ptr2->data + ptr3->data) == x)
// increment count
count++;
// required count of triplets
return count;
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node** head, int data)
{
// allocate node
struct Node* temp = new Node();
// put in the data
temp->data = data;
temp->next = temp->prev = NULL;
if ((*head) == NULL)
(*head) = temp;
else {
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// Driver program to test above
int main()
{
// start with an empty doubly linked list
struct Node* head = NULL;
// insert values in sorted order
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 17;
cout << "Count = "
<< countTriplets(head, x);
return 0;
}
|
constant
|
cubic
|
// C++ implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;
// structure of node of doubly linked list
struct Node {
int data;
struct Node* next, *prev;
};
// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node* head, int x)
{
struct Node* ptr, *ptr1, *ptr2;
int count = 0;
// unordered_map 'um' implemented as hash table
unordered_map<int, Node*> um;
// insert the <node data, node pointer> tuple in 'um'
for (ptr = head; ptr != NULL; ptr = ptr->next)
um[ptr->data] = ptr;
// generate all possible pairs
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next)
for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next) {
// p_sum - sum of elements in the current pair
int p_sum = ptr1->data + ptr2->data;
// if 'x-p_sum' is present in 'um' and either of the two nodes
// are not equal to the 'um[x-p_sum]' node
if (um.find(x - p_sum) != um.end() && um[x - p_sum] != ptr1
&& um[x - p_sum] != ptr2)
// increment count
count++;
}
// required count of triplets
// division by 3 as each triplet is counted 3 times
return (count / 3);
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node** head, int data)
{
// allocate node
struct Node* temp = new Node();
// put in the data
temp->data = data;
temp->next = temp->prev = NULL;
if ((*head) == NULL)
(*head) = temp;
else {
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// Driver program to test above
int main()
{
// start with an empty doubly linked list
struct Node* head = NULL;
// insert values in sorted order
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 17;
cout << "Count = "
<< countTriplets(head, x);
return 0;
}
|
linear
|
quadratic
|
// C++ implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;
// structure of node of doubly linked list
struct Node {
int data;
struct Node* next, *prev;
};
// function to count pairs whose sum equal to given 'value'
int countPairs(struct Node* first, struct Node* second, int value)
{
int count = 0;
// The loop terminates when either of two pointers
// become NULL, or they cross each other (second->next
// == first), or they become same (first == second)
while (first != NULL && second != NULL &&
first != second && second->next != first) {
// pair found
if ((first->data + second->data) == value) {
// increment count
count++;
// move first in forward direction
first = first->next;
// move second in backward direction
second = second->prev;
}
// if sum is greater than 'value'
// move second in backward direction
else if ((first->data + second->data) > value)
second = second->prev;
// else move first in forward direction
else
first = first->next;
}
// required count of pairs
return count;
}
// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node* head, int x)
{
// if list is empty
if (head == NULL)
return 0;
struct Node* current, *first, *last;
int count = 0;
// get pointer to the last node of
// the doubly linked list
last = head;
while (last->next != NULL)
last = last->next;
// traversing the doubly linked list
for (current = head; current != NULL; current = current->next) {
// for each current node
first = current->next;
// count pairs with sum(x - current->data) in the range
// first to last and add it to the 'count' of triplets
count += countPairs(first, last, x - current->data);
}
// required count of triplets
return count;
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node** head, int data)
{
// allocate node
struct Node* temp = new Node();
// put in the data
temp->data = data;
temp->next = temp->prev = NULL;
if ((*head) == NULL)
(*head) = temp;
else {
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// Driver program to test above
int main()
{
// start with an empty doubly linked list
struct Node* head = NULL;
// insert values in sorted order
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 17;
cout << "Count = "
<< countTriplets(head, x);
return 0;
}
|
constant
|
quadratic
|
/* C++ implementation to remove duplicates from a
sorted doubly linked list */
#include <bits/stdc++.h>
using namespace std;
/* a node of the doubly linked list */
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(struct Node** head_ref, struct Node* del)
{
/* base case */
if (*head_ref == NULL || del == NULL)
return;
/* If node to be deleted is head node */
if (*head_ref == del)
*head_ref = del->next;
/* Change next only if node to be deleted
is NOT the last node */
if (del->next != NULL)
del->next->prev = del->prev;
/* Change prev only if node to be deleted
is NOT the first node */
if (del->prev != NULL)
del->prev->next = del->next;
/* Finally, free the memory occupied by del*/
free(del);
}
/* function to remove duplicates from a
sorted doubly linked list */
void removeDuplicates(struct Node** head_ref)
{
/* if list is empty */
if ((*head_ref) == NULL)
return;
struct Node* current = *head_ref;
struct Node* next;
/* traverse the list till the last node */
while (current->next != NULL) {
/* Compare current node with next node */
if (current->data == current->next->data)
/* delete the node pointed to by
'current->next' */
deleteNode(head_ref, current->next);
/* else simply move to the next node */
else
current = current->next;
}
}
/* Function to insert a node at the beginning
of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly linked list */
void printList(struct Node* head)
{
/* if list is empty */
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Create the doubly linked list:
4<->4<->4<->4<->6<->8<->8<->10<->12<->12 */
push(&head, 12);
push(&head, 12);
push(&head, 10);
push(&head, 8);
push(&head, 8);
push(&head, 6);
push(&head, 4);
push(&head, 4);
push(&head, 4);
push(&head, 4);
cout << "Original Doubly linked list:n";
printList(head);
/* remove duplicate nodes */
removeDuplicates(&head);
cout << "\nDoubly linked list after"
" removing duplicates:n";
printList(head);
return 0;
}
|
constant
|
linear
|
/* C++ implementation to delete all occurrences
of a given key in a doubly linked list */
#include <bits/stdc++.h>
using namespace std;
/* a node of the doubly linked list */
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(struct Node** head_ref, struct Node* del)
{
/* base case */
if (*head_ref == NULL || del == NULL)
return;
/* If node to be deleted is head node */
if (*head_ref == del)
*head_ref = del->next;
/* Change next only if node to be deleted
is NOT the last node */
if (del->next != NULL)
del->next->prev = del->prev;
/* Change prev only if node to be deleted
is NOT the first node */
if (del->prev != NULL)
del->prev->next = del->next;
/* Finally, free the memory occupied by del*/
free(del);
}
/* function to delete all occurrences of the given
key 'x' */
void deleteAllOccurOfX(struct Node** head_ref, int x)
{
/* if list is empty */
if ((*head_ref) == NULL)
return;
struct Node* current = *head_ref;
struct Node* next;
/* traverse the list up to the end */
while (current != NULL) {
/* if node found with the value 'x' */
if (current->data == x) {
/* save current's next node in the
pointer 'next' */
next = current->next;
/* delete the node pointed to by
'current' */
deleteNode(head_ref, current);
/* update current */
current = next;
}
/* else simply move to the next node */
else
current = current->next;
}
}
/* Function to insert a node at the beginning
of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly
linked list */
void printList(struct Node* head)
{
/* if list is empty */
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Create the doubly linked list:
2<->2<->10<->8<->4<->2<->5<->2 */
push(&head, 2);
push(&head, 5);
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
push(&head, 2);
push(&head, 2);
cout << "Original Doubly linked list:n";
printList(head);
int x = 2;
/* delete all occurrences of 'x' */
deleteAllOccurOfX(&head, x);
cout << "\nDoubly linked list after deletion of "
<< x << ":n";
printList(head);
return 0;
}
|
constant
|
linear
|
// C++ implementation to remove duplicates from an
// unsorted doubly linked list
#include <bits/stdc++.h>
using namespace std;
// a node of the doubly linked list
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// Function to delete a node in a Doubly Linked List.
// head_ref --> pointer to head node pointer.
// del --> pointer to node to be deleted.
void deleteNode(struct Node** head_ref, struct Node* del)
{
// base case
if (*head_ref == NULL || del == NULL)
return;
// If node to be deleted is head node
if (*head_ref == del)
*head_ref = del->next;
// Change next only if node to be deleted
// is NOT the last node
if (del->next != NULL)
del->next->prev = del->prev;
// Change prev only if node to be deleted
// is NOT the first node
if (del->prev != NULL)
del->prev->next = del->next;
// Finally, free the memory occupied by del
free(del);
}
// function to remove duplicates from
// an unsorted doubly linked list
void removeDuplicates(struct Node** head_ref)
{
// if DLL is empty or if it contains only
// a single node
if ((*head_ref) == NULL ||
(*head_ref)->next == NULL)
return;
struct Node* ptr1, *ptr2;
// pick elements one by one
for (ptr1 = *head_ref; ptr1 != NULL; ptr1 = ptr1->next) {
ptr2 = ptr1->next;
// Compare the picked element with the
// rest of the elements
while (ptr2 != NULL) {
// if duplicate, then delete it
if (ptr1->data == ptr2->data) {
// store pointer to the node next to 'ptr2'
struct Node* next = ptr2->next;
// delete node pointed to by 'ptr2'
deleteNode(head_ref, ptr2);
// update 'ptr2'
ptr2 = next;
}
// else simply move to the next node
else
ptr2 = ptr2->next;
}
}
}
// Function to insert a node at the beginning
// of the Doubly Linked List
void push(struct Node** head_ref, int new_data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// since we are adding at the beginning,
// prev is always NULL
new_node->prev = NULL;
// link the old list off the new node
new_node->next = (*head_ref);
// change prev of head node to new node
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
// move the head to point to the new node
(*head_ref) = new_node;
}
// Function to print nodes in a given doubly
// linked list
void printList(struct Node* head)
{
// if list is empty
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// Create the doubly linked list:
// 8<->4<->4<->6<->4<->8<->4<->10<->12<->12
push(&head, 12);
push(&head, 12);
push(&head, 10);
push(&head, 4);
push(&head, 8);
push(&head, 4);
push(&head, 6);
push(&head, 4);
push(&head, 4);
push(&head, 8);
cout << "Original Doubly linked list:n";
printList(head);
/* remove duplicate nodes */
removeDuplicates(&head);
cout << "\nDoubly linked list after "
"removing duplicates:n";
printList(head);
return 0;
}
|
constant
|
quadratic
|
// C++ implementation to remove duplicates from an
// unsorted doubly linked list
#include <bits/stdc++.h>
using namespace std;
// a node of the doubly linked list
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// Function to delete a node in a Doubly Linked List.
// head_ref --> pointer to head node pointer.
// del --> pointer to node to be deleted.
void deleteNode(struct Node** head_ref, struct Node* del)
{
// base case
if (*head_ref == NULL || del == NULL)
return;
// If node to be deleted is head node
if (*head_ref == del)
*head_ref = del->next;
// Change next only if node to be deleted
// is NOT the last node
if (del->next != NULL)
del->next->prev = del->prev;
// Change prev only if node to be deleted
// is NOT the first node
if (del->prev != NULL)
del->prev->next = del->next;
// Finally, free the memory occupied by del
free(del);
}
// function to remove duplicates from
// an unsorted doubly linked list
void removeDuplicates(struct Node** head_ref)
{
// if doubly linked list is empty
if ((*head_ref) == NULL)
return;
// unordered_set 'us' implemented as hash table
unordered_set<int> us;
struct Node* current = *head_ref, *next;
// traverse up to the end of the list
while (current != NULL) {
// if current data is seen before
if (us.find(current->data) != us.end()) {
// store pointer to the node next to
// 'current' node
next = current->next;
// delete the node pointed to by 'current'
deleteNode(head_ref, current);
// update 'current'
current = next;
}
else {
// insert the current data in 'us'
us.insert(current->data);
// move to the next node
current = current->next;
}
}
}
// Function to insert a node at the beginning
// of the Doubly Linked List
void push(struct Node** head_ref, int new_data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// since we are adding at the beginning,
// prev is always NULL
new_node->prev = NULL;
// link the old list off the new node
new_node->next = (*head_ref);
// change prev of head node to new node
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
// move the head to point to the new node
(*head_ref) = new_node;
}
// Function to print nodes in a given doubly
// linked list
void printList(struct Node* head)
{
// if list is empty
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// Create the doubly linked list:
// 8<->4<->4<->6<->4<->8<->4<->10<->12<->12
push(&head, 12);
push(&head, 12);
push(&head, 10);
push(&head, 4);
push(&head, 8);
push(&head, 4);
push(&head, 6);
push(&head, 4);
push(&head, 4);
push(&head, 8);
cout << "Original Doubly linked list:n";
printList(head);
/* remove duplicate nodes */
removeDuplicates(&head);
cout << "\nDoubly linked list after "
"removing duplicates:n";
printList(head);
return 0;
}
|
linear
|
linear
|
// C++ implementation to sort a k sorted doubly
// linked list
#include<bits/stdc++.h>
using namespace std;
// a node of the doubly linked list
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// function to sort a k sorted doubly linked list
struct Node* sortAKSortedDLL(struct Node* head, int k)
{
if(head == NULL || head->next == NULL)
return head;
// perform on all the nodes in list
for(Node *i = head->next; i != NULL; i = i->next) {
Node *j = i;
// There will be atmost k swaps for each element in the list
// since each node is k steps away from its correct position
while(j->prev != NULL && j->data < j->prev->data) {
// swap j and j.prev node
Node* temp = j->prev->prev;
Node* temp2 = j->prev;
Node *temp3 = j->next;
j->prev->next = temp3;
j->prev->prev = j;
j->prev = temp;
j->next = temp2;
if(temp != NULL)
temp->next = j;
if(temp3 != NULL)
temp3->prev = temp2;
}
// if j is now the new head
// then reset head
if(j->prev == NULL)
head = j;
}
return head;
}
// Function to insert a node at the beginning
// of the Doubly Linked List
void push(struct Node** head_ref, int new_data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// since we are adding at the beginning,
// prev is always NULL
new_node->prev = NULL;
// link the old list of the new node
new_node->next = (*head_ref);
// change prev of head node to new node
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
// move the head to point to the new node
(*head_ref) = new_node;
}
// Function to print nodes in a given doubly linked list
void printList(struct Node* head)
{
// if list is empty
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// Create the doubly linked list:
// 3<->6<->2<->12<->56<->8
push(&head, 8);
push(&head, 56);
push(&head, 12);
push(&head, 2);
push(&head, 6);
push(&head, 3);
int k = 2;
cout << "Original Doubly linked list:\n";
printList(head);
// sort the biotonic DLL
head = sortAKSortedDLL(head, k);
cout << "\nDoubly linked list after sorting:\n";
printList(head);
return 0;
}
// This code is contributed by sachinejain74754.
|
constant
|
quadratic
|
// C++ implementation to sort a k sorted doubly
// linked list
#include <bits/stdc++.h>
using namespace std;
// a node of the doubly linked list
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// 'compare' function used to build up the
// priority queue
struct compare {
bool operator()(struct Node* p1, struct Node* p2)
{
return p1->data > p2->data;
}
};
// function to sort a k sorted doubly linked list
struct Node* sortAKSortedDLL(struct Node* head, int k)
{
// if list is empty
if (head == NULL)
return head;
// priority_queue 'pq' implemented as min heap with the
// help of 'compare' function
priority_queue<Node*, vector<Node*>, compare> pq;
struct Node* newHead = NULL, *last;
// Create a Min Heap of first (k+1) elements from
// input doubly linked list
for (int i = 0; head != NULL && i <= k; i++) {
// push the node on to 'pq'
pq.push(head);
// move to the next node
head = head->next;
}
// loop till there are elements in 'pq'
while (!pq.empty()) {
// place root or top of 'pq' at the end of the
// result sorted list so far having the first node
// pointed to by 'newHead'
// and adjust the required links
if (newHead == NULL) {
newHead = pq.top();
newHead->prev = NULL;
// 'last' points to the last node
// of the result sorted list so far
last = newHead;
}
else {
last->next = pq.top();
pq.top()->prev = last;
last = pq.top();
}
// remove element from 'pq'
pq.pop();
// if there are more nodes left in the input list
if (head != NULL) {
// push the node on to 'pq'
pq.push(head);
// move to the next node
head = head->next;
}
}
// making 'next' of last node point to NULL
last->next = NULL;
// new head of the required sorted DLL
return newHead;
}
// Function to insert a node at the beginning
// of the Doubly Linked List
void push(struct Node** head_ref, int new_data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// since we are adding at the beginning,
// prev is always NULL
new_node->prev = NULL;
// link the old list off the new node
new_node->next = (*head_ref);
// change prev of head node to new node
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
// move the head to point to the new node
(*head_ref) = new_node;
}
// Function to print nodes in a given doubly linked list
void printList(struct Node* head)
{
// if list is empty
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// Create the doubly linked list:
// 3<->6<->2<->12<->56<->8
push(&head, 8);
push(&head, 56);
push(&head, 12);
push(&head, 2);
push(&head, 6);
push(&head, 3);
int k = 2;
cout << "Original Doubly linked list:\n";
printList(head);
// sort the biotonic DLL
head = sortAKSortedDLL(head, k);
cout << "\nDoubly linked list after sorting:\n";
printList(head);
return 0;
}
|
constant
|
nlogn
|
// C++ program to convert a given Binary Tree to Doubly Linked List
#include <bits/stdc++.h>
// Structure for tree and linked list
struct Node {
int data;
Node *left, *right;
};
// Utility function for allocating node for Binary
// Tree.
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
// A simple recursive function to convert a given
// Binary tree to Doubly Linked List
// root --> Root of Binary Tree
// head --> Pointer to head node of created doubly linked list
void BToDLL(Node* root, Node*& head)
{
// Base cases
if (root == NULL)
return;
// Recursively convert right subtree
BToDLL(root->right, head);
// insert root into DLL
root->right = head;
// Change left pointer of previous head
if (head != NULL)
head->left = root;
// Change head of Doubly linked list
head = root;
// Recursively convert left subtree
BToDLL(root->left, head);
}
// Utility function for printing double linked list.
void printList(Node* head)
{
printf("Extracted Double Linked list is:\n");
while (head) {
printf("%d ", head->data);
head = head->right;
}
}
// Driver program to test above function
int main()
{
/* Constructing below tree
5
/ \
3 6
/ \ \
1 4 8
/ \ / \
0 2 7 9 */
Node* root = newNode(5);
root->left = newNode(3);
root->right = newNode(6);
root->left->left = newNode(1);
root->left->right = newNode(4);
root->right->right = newNode(8);
root->left->left->left = newNode(0);
root->left->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(9);
Node* head = NULL;
BToDLL(root, head);
printList(head);
return 0;
}
|
linear
|
linear
|
/* C++ program to insetail nodes in doubly
linked list such that list remains in
ascending order on printing from left
to right */
#include <bits/stdc++.h>
using namespace std;
// A linked list node
class Node
{
public:
Node *prev;
int info;
Node *next;
};
// Function to insetail new node
void nodeInsetail(Node **head,
Node **tail,
int key)
{
Node *p = new Node();
p->info = key;
p->next = NULL;
// If first node to be insetailed in doubly
// linked list
if ((*head) == NULL)
{
(*head) = p;
(*tail) = p;
(*head)->prev = NULL;
return;
}
// If node to be insetailed has value less
// than first node
if ((p->info) < ((*head)->info))
{
p->prev = NULL;
(*head)->prev = p;
p->next = (*head);
(*head) = p;
return;
}
// If node to be insetailed has value more
// than last node
if ((p->info) > ((*tail)->info))
{
p->prev = (*tail);
(*tail)->next = p;
(*tail) = p;
return;
}
// Find the node before which we need to
// insert p.
Node *temp = (*head)->next;
while ((temp->info) < (p->info))
temp = temp->next;
// Insert new node before temp
(temp->prev)->next = p;
p->prev = temp->prev;
temp->prev = p;
p->next = temp;
}
// Function to print nodes in from left to right
void printList(Node *temp)
{
while (temp != NULL)
{
cout << temp->info << " ";
temp = temp->next;
}
}
// Driver program to test above functions
int main()
{
Node *left = NULL, *right = NULL;
nodeInsetail(&left, &right, 30);
nodeInsetail(&left, &right, 50);
nodeInsetail(&left, &right, 90);
nodeInsetail(&left, &right, 10);
nodeInsetail(&left, &right, 40);
nodeInsetail(&left, &right, 110);
nodeInsetail(&left, &right, 60);
nodeInsetail(&left, &right, 95);
nodeInsetail(&left, &right, 23);
cout<<"Doubly linked list on printing"
" from left to right\n";
printList(left);
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
#include<iostream>
using namespace std;
class Node
{
public:
char data;
Node* next;
Node* pre;
Node(int data)
{
this->data=data;
pre=NULL;
next=NULL;
}
};
void insertAtHead(Node* &head, int data)
{
Node* n = new Node(data);
if(head==NULL)
{
head=n;
return;
}
n->next=head;
head->pre=n;
head=n;
return;
}
void insertAtTail(Node* &head, int data)
{
if(head==NULL)
{
insertAtHead(head,data);
return;
}
Node* temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
Node* n=new Node(data);
temp->next=n;
n->pre=temp;
return;
}
void display(Node* head)
{
while(head!=NULL)
{
cout << head->data << "-->";
head=head->next;
}
cout << "NULL\n";
}
void rotateByN(Node *&head, int pos)
{
if (pos == 0)
return;
Node *curr = head;
while (pos)
{
curr = curr->next;
pos--;
}
Node *tail = curr->pre;
Node *NewHead = curr;
tail->next = NULL;
curr->pre = NULL;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = head;
head->pre = curr;
head = NewHead;
}
int main()
{
Node* head=NULL;
insertAtTail(head,'a');
insertAtTail(head,'b');
insertAtTail(head,'c');
insertAtTail(head,'d');
insertAtTail(head,'e');
int n=2;
cout << "\nBefore Rotation : \n";
display(head);
rotateByN(head,n);
cout << "\nAfter Rotation : \n";
display(head);
cout << "\n\n";
return 0;
}
|
constant
|
linear
|
// C++ implementation to reverse a doubly linked list
// in groups of given size without recursion
// Iterative Method
#include <iostream>
using namespace std;
// Represents a node of doubly linked list
struct Node {
int data;
Node *next, *prev;
};
// function to get a new node
Node* getNode(int data)
{
// allocating node
Node* new_node = new Node();
new_node->data = data;
new_node->next = new_node->prev = NULL;
return new_node;
}
// function to insert a node at the beginning
// of the Doubly Linked List
Node* push(Node* head, Node* new_node)
{
// since we are adding at the beginning,
// prev is always NULL
new_node->prev = NULL;
// link the old list off the new node
new_node->next = head;
// change prev of head node to new node
if (head != NULL)
head->prev = new_node;
// move the head to point to the new node
head = new_node;
return head;
}
// function to reverse a doubly linked list
// in groups of given size
Node* revListInGroupOfGivenSize(Node* head, int k)
{
if (!head)
return head;
Node* st = head;
Node* globprev = NULL;
Node* ans = NULL;
while (st) {
int count = 1; // to count k nodes
Node* curr = st;
Node* prev = NULL;
Node* next = NULL;
while (curr && count <= k) { // reversing k nodes
next = curr->next;
curr->prev = next;
curr->next = prev;
prev = curr;
curr = next;
count++;
}
if (!ans) {
ans = prev; // to store ans i.e the new head
ans->prev = NULL;
}
if (!globprev)
globprev = st; // assigning the last node of the
// reversed k nodes
else {
globprev->next = prev;
prev->prev
= globprev; // connecting last node of last
// k group to the first node of
// present k group
globprev = st;
}
st = curr; // advancing the pointer for the next k
// group
}
return ans;
}
// Function to print nodes in a
// given doubly linked list
void printList(Node* head)
{
while (head) {
cout << head->data << " ";
head = head->next;
}
}
// Driver code
int main()
{
// Start with the empty list
Node* head = NULL;
// Create doubly linked: 10<->8<->4<->2
head = push(head, getNode(2));
head = push(head, getNode(4));
head = push(head, getNode(8));
head = push(head, getNode(10));
int k = 2;
cout << "Original list: ";
printList(head);
// Reverse doubly linked list in groups of
// size 'k'
head = revListInGroupOfGivenSize(head, k);
cout << "\nModified list: ";
printList(head);
return 0;
}
// This code is contributed by Tapesh (tapeshdua420)
|
constant
|
linear
|
// C++ program to illustrate inserting a Node in
// a Circular Doubly Linked list in begging, end
// and middle
#include <bits/stdc++.h>
using namespace std;
// Structure of a Node
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// Function to insert at the end
void insertEnd(struct Node** start, int value)
{
// If the list is empty, create a single node
// circular and doubly list
if (*start == NULL) {
struct Node* new_node = new Node;
new_node->data = value;
new_node->next = new_node->prev = new_node;
*start = new_node;
return;
}
// If list is not empty
/* Find last node */
Node* last = (*start)->prev;
// Create Node dynamically
struct Node* new_node = new Node;
new_node->data = value;
// Start is going to be next of new_node
new_node->next = *start;
// Make new node previous of start
(*start)->prev = new_node;
// Make last previous of new node
new_node->prev = last;
// Make new node next of old last
last->next = new_node;
}
// Function to insert Node at the beginning
// of the List,
void insertBegin(struct Node** start, int value)
{
// Pointer points to last Node
struct Node* last = (*start)->prev;
struct Node* new_node = new Node;
new_node->data = value; // Inserting the data
// setting up previous and next of new node
new_node->next = *start;
new_node->prev = last;
// Update next and previous pointers of start
// and last.
last->next = (*start)->prev = new_node;
// Update start pointer
*start = new_node;
}
// Function to insert node with value as value1.
// The new node is inserted after the node with
// with value2
void insertAfter(struct Node** start, int value1,
int value2)
{
struct Node* new_node = new Node;
new_node->data = value1; // Inserting the data
// Find node having value2 and next node of it
struct Node* temp = *start;
while (temp->data != value2)
temp = temp->next;
struct Node* next = temp->next;
// insert new_node between temp and next.
temp->next = new_node;
new_node->prev = temp;
new_node->next = next;
next->prev = new_node;
}
void display(struct Node* start)
{
struct Node* temp = start;
printf("\nTraversal in forward direction \n");
while (temp->next != start) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("%d ", temp->data);
printf("\nTraversal in reverse direction \n");
Node* last = start->prev;
temp = last;
while (temp->prev != last) {
printf("%d ", temp->data);
temp = temp->prev;
}
printf("%d ", temp->data);
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* start = NULL;
// Insert 5. So linked list becomes 5->NULL
insertEnd(&start, 5);
// Insert 4 at the beginning. So linked
// list becomes 4->5
insertBegin(&start, 4);
// Insert 7 at the end. So linked list
// becomes 4->5->7
insertEnd(&start, 7);
// Insert 8 at the end. So linked list
// becomes 4->5->7->8
insertEnd(&start, 8);
// Insert 6, after 5. So linked list
// becomes 4->5->6->7->8
insertAfter(&start, 6, 5);
printf("Created circular doubly linked list is: ");
display(start);
return 0;
}
|
constant
|
linear
|
// C++ program to implement Stack
// using linked list so that reverse
// can be done with O(1) extra space.
#include<bits/stdc++.h>
using namespace std;
class StackNode {
public:
int data;
StackNode *next;
StackNode(int data)
{
this->data = data;
this->next = NULL;
}
};
class Stack {
StackNode *top;
public:
// Push and pop operations
void push(int data)
{
if (top == NULL) {
top = new StackNode(data);
return;
}
StackNode *s = new StackNode(data);
s->next = top;
top = s;
}
StackNode* pop()
{
StackNode *s = top;
top = top->next;
return s;
}
// prints contents of stack
void display()
{
StackNode *s = top;
while (s != NULL) {
cout << s->data << " ";
s = s->next;
}
cout << endl;
}
// Reverses the stack using simple
// linked list reversal logic.
void reverse()
{
StackNode *prev, *cur, *succ;
cur = prev = top;
cur = cur->next;
prev->next = NULL;
while (cur != NULL) {
succ = cur->next;
cur->next = prev;
prev = cur;
cur = succ;
}
top = prev;
}
};
// driver code
int main()
{
Stack *s = new Stack();
s->push(1);
s->push(2);
s->push(3);
s->push(4);
cout << "Original Stack" << endl;;
s->display();
cout << endl;
// reverse
s->reverse();
cout << "Reversed Stack" << endl;
s->display();
return 0;
}
// This code is contributed by Chhavi.
|
constant
|
linear
|
// C++ program to implement unrolled linked list
// and traversing it.
#include <bits/stdc++.h>
using namespace std;
#define maxElements 4
// Unrolled Linked List Node
class Node
{
public:
int numElements;
int array[maxElements];
Node *next;
};
/* Function to traverse an unrolled linked list
and print all the elements*/
void printUnrolledList(Node *n)
{
while (n != NULL)
{
// Print elements in current node
for (int i=0; i<n->numElements; i++)
cout<<n->array[i]<<" ";
// Move to next node
n = n->next;
}
}
// Program to create an unrolled linked list
// with 3 Nodes
int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
// allocate 3 Nodes
head = new Node();
second = new Node();
third = new Node();
// Let us put some values in second node (Number
// of values must be less than or equal to
// maxElement)
head->numElements = 3;
head->array[0] = 1;
head->array[1] = 2;
head->array[2] = 3;
// Link first Node with the second Node
head->next = second;
// Let us put some values in second node (Number
// of values must be less than or equal to
// maxElement)
second->numElements = 3;
second->array[0] = 4;
second->array[1] = 5;
second->array[2] = 6;
// Link second Node with the third Node
second->next = third;
// Let us put some values in third node (Number
// of values must be less than or equal to
// maxElement)
third->numElements = 3;
third->array[0] = 7;
third->array[1] = 8;
third->array[2] = 9;
third->next = NULL;
printUnrolledList(head);
return 0;
}
// This is code is contributed by rathbhupendra
|
linear
|
linear
|
// C++ program to construct the maximum sum linked
// list out of two given sorted lists
#include<bits/stdc++.h>
using namespace std;
//A linked list node
struct Node
{
int data; //data belong to that node
Node *next; //next pointer
};
// Push the data to the head of the linked list
void push(Node **head, int data)
{
//Allocation memory to the new node
Node *newnode = new Node;
//Assigning data to the new node
newnode->data = data;
//Adjusting next pointer of the new node
newnode->next = *head;
//New node becomes the head of the list
*head = newnode;
}
// Method that adjusts the pointers and prints the final list
void finalMaxSumList(Node *a, Node *b)
{
Node *result = NULL;
// Assigning pre and cur to the head of the
// linked list.
Node *pre1 = a, *curr1 = a;
Node *pre2 = b, *curr2 = b;
// Till either of the current pointers is not
// NULL execute the loop
while (curr1 != NULL || curr2 != NULL)
{
// Keeping 2 local variables at the start of every
// loop run to keep track of the sum between pre
// and cur pointer elements.
int sum1 = 0, sum2 = 0;
// Calculating sum by traversing the nodes of linked
// list as the merging of two linked list. The loop
// stops at a common node
while (curr1!=NULL && curr2!=NULL && curr1->data!=curr2->data)
{
if (curr1->data < curr2->data)
{
sum1 += curr1->data;
curr1 = curr1->next;
}
else // (curr2->data < curr1->data)
{
sum2 += curr2->data;
curr2 = curr2->next;
}
}
// If either of current pointers becomes NULL
// carry on the sum calculation for other one.
if (curr1 == NULL)
{
while (curr2 != NULL)
{
sum2 += curr2->data;
curr2 = curr2->next;
}
}
if (curr2 == NULL)
{
while (curr1 != NULL)
{
sum1 += curr1->data;
curr1 = curr1->next;
}
}
// First time adjustment of resultant head based on
// the maximum sum.
if (pre1 == a && pre2 == b)
result = (sum1 > sum2)? pre1 : pre2;
// If pre1 and pre2 don't contain the head pointers of
// lists adjust the next pointers of previous pointers.
else
{
if (sum1 > sum2)
pre2->next = pre1->next;
else
pre1->next = pre2->next;
}
// Adjusting previous pointers
pre1 = curr1, pre2 = curr2;
// If curr1 is not NULL move to the next.
if (curr1)
curr1 = curr1->next;
// If curr2 is not NULL move to the next.
if (curr2)
curr2 = curr2->next;
}
// Print the resultant list.
while (result != NULL)
{
cout << result->data << " ";
result = result->next;
}
}
//Main driver program
int main()
{
//Linked List 1 : 1->3->30->90->110->120->NULL
//Linked List 2 : 0->3->12->32->90->100->120->130->NULL
Node *head1 = NULL, *head2 = NULL;
push(&head1, 120);
push(&head1, 110);
push(&head1, 90);
push(&head1, 30);
push(&head1, 3);
push(&head1, 1);
push(&head2, 130);
push(&head2, 120);
push(&head2, 100);
push(&head2, 90);
push(&head2, 32);
push(&head2, 12);
push(&head2, 3);
push(&head2, 0);
finalMaxSumList(head1, head2);
return 0;
}
|
constant
|
linear
|
// C++ program to find fractional node in a linked list
#include <bits/stdc++.h>
/* Linked list node */
struct Node {
int data;
Node* next;
};
/* Function to create a new node with given data */
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
/* Function to find fractional node in the linked list */
Node* fractionalNodes(Node* head, int k)
{
// Corner cases
if (k <= 0 || head == NULL)
return NULL;
Node* fractionalNode = NULL;
// Traverse the given list
int i = 0;
for (Node* temp = head; temp != NULL; temp = temp->next) {
// For every k nodes, we move fractionalNode one
// step ahead.
if (i % k == 0) {
// First time we see a multiple of k
if (fractionalNode == NULL)
fractionalNode = head;
else
fractionalNode = fractionalNode->next;
}
i++;
}
return fractionalNode;
}
// A utility function to print a linked list
void printList(Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
/* Driver program to test above function */
int main(void)
{
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
int k = 2;
printf("List is ");
printList(head);
Node* answer = fractionalNodes(head, k);
printf("\nFractional node is ");
printf("%d\n", answer->data);
return 0;
}
|
constant
|
linear
|
// C++ program to find modular node in a linked list
#include <bits/stdc++.h>
/* Linked list node */
struct Node {
int data;
Node* next;
};
/* Function to create a new node with given data */
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
/* Function to find modular node in the linked list */
Node* modularNode(Node* head, int k)
{
// Corner cases
if (k <= 0 || head == NULL)
return NULL;
// Traverse the given list
int i = 1;
Node* modularNode = NULL;
for (Node* temp = head; temp != NULL; temp = temp->next) {
if (i % k == 0)
modularNode = temp;
i++;
}
return modularNode;
}
/* Driver program to test above function */
int main(void)
{
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
int k = 2;
Node* answer = modularNode(head, k);
printf("\nModular node is ");
if (answer != NULL)
printf("%d\n", answer->data);
else
printf("null\n");
return 0;
}
|
constant
|
linear
|
// C++ Program to find smallest and largest
// elements in singly linked list.
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node {
int data;
struct Node* next;
};
// Function that returns the largest element
// from the linked list.
int largestElement(struct Node* head)
{
// Declare a max variable and initialize
// it with INT_MIN value.
// INT_MIN is integer type and its value
// is -32767 or less.
int max = INT_MIN;
// Check loop while head not equal to NULL
while (head != NULL) {
// If max is less than head->data then
// assign value of head->data to max
// otherwise node point to next node.
if (max < head->data)
max = head->data;
head = head->next;
}
return max;
}
// Function that returns smallest element
// from the linked list.
int smallestElement(struct Node* head)
{
// Declare a min variable and initialize
// it with INT_MAX value.
// INT_MAX is integer type and its value
// is 32767 or greater.
int min = INT_MAX;
// Check loop while head not equal to NULL
while (head != NULL) {
// If min is greater than head->data then
// assign value of head->data to min
// otherwise node point to next node.
if (min > head->data)
min = head->data;
head = head->next;
}
return min;
}
// Function that push the element in linked list.
void push(struct Node** head, int data)
{
// Allocate dynamic memory for newNode.
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
// Assign the data into newNode.
newNode->data = data;
// newNode->next assign the address of
// head node.
newNode->next = (*head);
// newNode become the headNode.
(*head) = newNode;
}
// Display linked list.
void printList(struct Node* head)
{
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
cout << "NULL" << endl;
}
// Driver program to test the functions
int main()
{
// Start with empty list
struct Node* head = NULL;
// Using push() function to construct
// singly linked list
// 17->22->13->14->15
push(&head, 15);
push(&head, 14);
push(&head, 13);
push(&head, 22);
push(&head, 17);
cout << "Linked list is : " << endl;
// Call printList() function to display
// the linked list.
printList(head);
cout << "Maximum element in linked list:";
// Call largestElement() function to get largest
// element in linked list.
cout << largestElement(head) << endl;
cout << "Minimum element in linked list:";
// Call smallestElement() function to get smallest
// element in linked list.
cout << smallestElement(head) << endl;
return 0;
}
|
constant
|
linear
|
/* C++ program to arrange consonants and
vowels nodes in a linked list */
#include<bits/stdc++.h>
using namespace std;
/* A linked list node */
struct Node
{
char data;
struct Node *next;
};
/* Function to add new node to the List */
Node *newNode(char key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// utility function to print linked list
void printlist(Node *head)
{
if (! head)
{
cout << "Empty List\n";
return;
}
while (head != NULL)
{
cout << head->data << " ";
if (head->next)
cout << "-> ";
head = head->next;
}
cout << endl;
}
// utility function for checking vowel
bool isVowel(char x)
{
return (x == 'a' || x == 'e' || x == 'i' ||
x == 'o' || x == 'u');
}
/* function to arrange consonants and
vowels nodes */
Node *arrange(Node *head)
{
Node *newHead = head;
// for keep track of vowel
Node *latestVowel;
Node *curr = head;
// list is empty
if (head == NULL)
return NULL;
// We need to discover the first vowel
// in the list. It is going to be the
// returned head, and also the initial
// latestVowel.
if (isVowel(head->data))
// first element is a vowel. It will
// also be the new head and the initial
// latestVowel;
latestVowel = head;
else
{
// First element is not a vowel. Iterate
// through the list until we find a vowel.
// Note that curr points to the element
// *before* the element with the vowel.
while (curr->next != NULL &&
!isVowel(curr->next->data))
curr = curr->next;
// This is an edge case where there are
// only consonants in the list.
if (curr->next == NULL)
return head;
// Set the initial latestVowel and the
// new head to the vowel item that we found.
// Relink the chain of consonants after
// that vowel item:
// old_head_consonant->consonant1->consonant2->
// vowel->rest_of_list becomes
// vowel->old_head_consonant->consonant1->
// consonant2->rest_of_list
latestVowel = newHead = curr->next;
curr->next = curr->next->next;
latestVowel->next = head;
}
// Now traverse the list. Curr is always the item
// *before* the one we are checking, so that we
// can use it to re-link.
while (curr != NULL && curr->next != NULL)
{
if (isVowel(curr->next->data))
{
// The next discovered item is a vowel
if (curr == latestVowel)
{
// If it comes directly after the
// previous vowel, we don't need to
// move items around, just mark the
// new latestVowel and advance curr.
latestVowel = curr = curr->next;
}
else
{
// But if it comes after an intervening
// chain of consonants, we need to chain
// the newly discovered vowel right after
// the old vowel. Curr is not changed as
// after the re-linking it will have a
// new next, that has not been checked yet,
// and we always keep curr at one before
// the next to check.
Node *temp = latestVowel->next;
// Chain in new vowel
latestVowel->next = curr->next;
// Advance latestVowel
latestVowel = latestVowel->next;
// Remove found vowel from previous place
curr->next = curr->next->next;
// Re-link chain of consonants after latestVowel
latestVowel->next = temp;
}
}
else
{
// No vowel in the next element, advance curr.
curr = curr->next;
}
}
return newHead;
}
// Driver code
int main()
{
Node *head = newNode('a');
head->next = newNode('b');
head->next->next = newNode('c');
head->next->next->next = newNode('e');
head->next->next->next->next = newNode('d');
head->next->next->next->next->next = newNode('o');
head->next->next->next->next->next->next = newNode('x');
head->next->next->next->next->next->next->next = newNode('i');
printf("Linked list before :\n");
printlist(head);
head = arrange(head);
printf("Linked list after :\n");
printlist(head);
return 0;
}
|
constant
|
linear
|
/* C++ program to arrange consonants and
vowels nodes in a linked list */
#include <bits/stdc++.h>
using namespace std;
/* A linked list node */
struct Node {
char data;
struct Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
/* Function to add new node to the List */
void append(struct Node** headRef, char data)
{
struct Node* new_node = new Node(data);
struct Node* last = *headRef;
if (*headRef == NULL) {
*headRef = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
// utility function to print linked list
void printlist(Node* head)
{
if (!head) {
cout << "Empty List\n";
return;
}
while (head != NULL) {
cout << head->data << " ";
if (head->next)
cout << "-> ";
head = head->next;
}
cout << endl;
}
/* function to arrange consonants and
vowels nodes */
struct Node* arrange(Node* head)
{
Node *vowel = NULL, *consonant = NULL, *start = NULL,
*end = NULL;
while (head != NULL) {
char x = head->data;
// Checking the current node data is vowel or
// not
if (x == 'a' || x == 'e' || x == 'i' || x == 'o'
|| x == 'u') {
if (!vowel) {
vowel = new Node(x);
start = vowel;
}
else {
vowel->next = new Node(x);
vowel = vowel->next;
}
}
else {
if (!consonant) {
consonant = new Node(x);
end = consonant;
}
else {
consonant->next = new Node(x);
consonant = consonant->next;
}
}
head = head->next;
}
// In case when there is no vowel in the incoming LL
// then we have to return the head of the consonant LL
if (start == NULL)
return end;
// Connecting the vowel and consonant LL
vowel->next = end;
return start;
}
// Driver code
int main()
{
struct Node* head = NULL;
append(&head, 'a');
append(&head, 'b');
append(&head, 'c');
append(&head, 'e');
append(&head, 'd');
append(&head, 'o');
append(&head, 'x');
append(&head, 'i');
printf("Linked list before :\n");
printlist(head);
head = arrange(head);
printf("Linked list after :\n");
printlist(head);
return 0;
}
// This code is contributed by Aditya Kumar
|
linear
|
linear
|
// C++ program to partition a linked list around a
// given value.
#include<bits/stdc++.h>
using namespace std;
/* Link list Node */
struct Node
{
int data;
struct Node* next;
};
// A utility function to create a new node
Node *newNode(int data)
{
struct Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// Function to make a new list(using the existing
// nodes) and return head of new list.
struct Node *partition(struct Node *head, int x)
{
/* Let us initialize start and tail nodes of
new list */
struct Node *tail = head;
// Now iterate original list and connect nodes
Node *curr = head;
while (curr != NULL)
{
struct Node *next = curr->next;
if (curr->data < x)
{
/* Insert node at head. */
curr->next = head;
head = curr;
}
else // Append to the list of greater values
{
/* Insert node at tail. */
tail->next = curr;
tail = curr;
}
curr = next;
}
tail->next = NULL;
// The head has changed, so we need
// to return it to the user.
return head;
}
/* Function to print linked list */
void printList(struct Node *head)
{
struct Node *temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
// Driver program to run the case
int main()
{
/* Start with the empty list */
struct Node* head = newNode(3);
head->next = newNode(5);
head->next->next = newNode(8);
head->next->next->next = newNode(2);
head->next->next->next->next = newNode(10);
head->next->next->next->next->next = newNode(2);
head->next->next->next->next->next->next = newNode(1);
int x = 5;
head = partition(head, x);
printList(head);
return 0;
}
|
constant
|
linear
|
// C++ implementation to modify the contents of
// the linked list
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node
{
int data;
struct Node* next;
};
/* function prototype for printing the list */
void printList(struct Node*);
/* Function to insert a node at the beginning of
the linked list */
void push(struct Node **head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list at the end of the new node */
new_node->next = *head_ref;
/* move the head to point to the new node */
*head_ref = new_node;
}
/* Split the nodes of the given list
into front and back halves,
and return the two lists
using the reference parameters.
Uses the fast/slow pointer strategy. */
void frontAndBackSplit(struct Node *head,
struct Node **front_ref, struct Node **back_ref)
{
Node *slow, *fast;
slow = head;
fast = head->next;
/* Advance 'fast' two nodes, and
advance 'slow' one node */
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
/* 'slow' is before the midpoint in the list,
so split it in two at that point. */
*front_ref = head;
*back_ref = slow->next;
slow->next = NULL;
}
/* Function to reverse the linked list */
void reverseList(struct Node **head_ref)
{
struct Node *current, *prev, *next;
current = *head_ref;
prev = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
// perform the required subtraction operation on
// the 1st half of the linked list
void modifyTheContentsOf1stHalf(struct Node *front,
struct Node *back)
{
// traversing both the lists simultaneously
while (back != NULL)
{
// subtraction operation and node data
// modification
front->data = front->data - back->data;
front = front->next;
back = back->next;
}
}
// function to concatenate the 2nd(back) list at the end of
// the 1st(front) list and returns the head of the new list
struct Node* concatFrontAndBackList(struct Node *front,
struct Node *back)
{
struct Node *head = front;
while (front->next != NULL)
front = front->next;
front->next = back;
return head;
}
// function to modify the contents of the linked list
struct Node* modifyTheList(struct Node *head)
{
// if list is empty or contains only single node
if (!head || head->next == NULL)
return head;
struct Node *front, *back;
// split the list into two halves
// front and back lists
frontAndBackSplit(head, &front, &back);
// reverse the 2nd(back) list
reverseList(&back);
// modify the contents of 1st half
modifyTheContentsOf1stHalf(front, back);
// agains reverse the 2nd(back) list
reverseList(&back);
// concatenating the 2nd list back to the
// end of the 1st list
head = concatFrontAndBackList(front, back);
// pointer to the modified list
return head;
}
// function to print the linked list
void printList(struct Node *head)
{
if (!head)
return;
while (head->next != NULL)
{
cout << head->data << " -> ";
head = head->next;
}
cout << head->data << endl;
}
// Driver program to test above
int main()
{
struct Node *head = NULL;
// creating the linked list
push(&head, 10);
push(&head, 7);
push(&head, 12);
push(&head, 8);
push(&head, 9);
push(&head, 2);
// modify the linked list
head = modifyTheList(head);
// print the modified linked list
cout << "Modified List:" << endl;
printList(head);
return 0;
}
|
constant
|
linear
|
// C++ implementation to modify the
// contents of the linked list
#include <bits/stdc++.h>
using namespace std;
// Linked list node
struct Node
{
int data;
struct Node* next;
};
// function prototype for printing the list
void printList(struct Node*);
// Function to insert a node at the
// beginning of the linked list
void push(struct Node **head_ref, int new_data)
{
// allocate node
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// link the old list at the end of the new node
new_node->next = *head_ref;
// move the head to point to the new node
*head_ref = new_node;
}
// function to print the linked list
void printList(struct Node *head)
{
if (!head)
return;
while (head->next != NULL)
{
cout << head->data << " -> ";
head = head->next;
}
cout << head->data << endl;
}
// Function to middle node of list.
Node* find_mid(Node *head)
{
Node *temp = head, *slow = head, *fast = head ;
while(fast && fast->next)
{
// Advance 'fast' two nodes, and
// advance 'slow' one node
slow = slow->next ;
fast = fast->next->next ;
}
// If number of nodes are odd then update slow
// by slow->next;
if(fast)
slow = slow->next ;
return slow ;
}
// function to modify the contents of the linked list.
void modifyTheList(struct Node *head, struct Node *slow)
{
// Create Stack.
stack <int> s;
Node *temp = head ;
while(slow)
{
s.push( slow->data ) ;
slow = slow->next ;
}
// Traverse the list by using temp until stack is empty.
while( !s.empty() )
{
temp->data = temp->data - s.top() ;
temp = temp->next ;
s.pop() ;
}
}
// Driver program to test above
int main()
{
struct Node *head = NULL, *mid ;
// creating the linked list
push(&head, 10);
push(&head, 7);
push(&head, 12);
push(&head, 8);
push(&head, 9);
push(&head, 2);
// Call Function to Find the starting point of second half of list.
mid = find_mid(head) ;
// Call function to modify the contents of the linked list.
modifyTheList( head, mid);
// print the modified linked list
cout << "Modified List:" << endl;
printList(head);
return 0;
}
// This is contributed by Mr. Gera
|
linear
|
linear
|
// C++ program to rotate a matrix
// by 90 degrees
#include <bits/stdc++.h>
#define N 4
using namespace std;
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in
// anti-clockwise direction
void rotateMatrix(int mat[][N])
{
// Consider all squares one by one
for (int x = 0; x < N / 2; x++) {
// Consider elements in group
// of 4 in current square
for (int y = x; y < N - x - 1; y++) {
// Store current cell in
// temp variable
int temp = mat[x][y];
// Move values from right to top
mat[x][y] = mat[y][N - 1 - x];
// Move values from bottom to right
mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y];
// Move values from left to bottom
mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x];
// Assign temp to left
mat[N - 1 - y][x] = temp;
}
}
}
// Function to print the matrix
void displayMatrix(int mat[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
/* Driver code */
int main()
{
// Test Case 1
int mat[N][N] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
// Function call
rotateMatrix(mat);
// Print rotated matrix
displayMatrix(mat);
return 0;
}
|
constant
|
quadratic
|
// C++ program to rotate a matrix
// by 90 degrees
#include <bits/stdc++.h>
using namespace std;
#define N 4
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in
// anti-clockwise direction
void rotateMatrix(int mat[][N])
{ // REVERSE every row
for (int i = 0; i < N; i++)
reverse(mat[i], mat[i] + N);
// Performing Transpose
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++)
swap(mat[i][j], mat[j][i]);
}
}
// Function to print the matrix
void displayMatrix(int mat[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
/* Driver code */
int main()
{
int mat[N][N] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
// Function call
rotateMatrix(mat);
// Print rotated matrix
displayMatrix(mat);
return 0;
}
|
constant
|
quadratic
|
#include <bits/stdc++.h>
using namespace std;
//Function to rotate matrix anticlockwise by 90 degrees.
void rotateby90(vector<vector<int> >& matrix)
{
int n=matrix.size();
int mid;
if(n%2==0)
mid=n/2-1;
else
mid=n/2;
for(int i=0,j=n-1;i<=mid;i++,j--)
{
for(int k=0;k<j-i;k++)
{
swap(matrix[i][j-k],matrix[j][i+k]); //ru ld
swap(matrix[i+k][i],matrix[j][i+k]); //lu ld
swap(matrix[i][j-k],matrix[j-k][j]); //ru rd
}
}
}
void printMatrix(vector<vector<int>>& arr)
{
int n=arr.size();
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
int main() {
vector<vector<int>> arr = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateby90(arr);
printMatrix(arr);
return 0;
}
|
constant
|
quadratic
|
// C++ program to rotate a matrix by 180 degrees
#include <bits/stdc++.h>
#define N 3
using namespace std;
// Function to Rotate the matrix by 180 degree
void rotateMatrix(int mat[][N])
{
// Simply print from last cell to first cell.
for (int i = N - 1; i >= 0; i--) {
for (int j = N - 1; j >= 0; j--)
printf("%d ", mat[i][j]);
printf("\n");
}
}
// Driven code
int main()
{
int mat[N][N] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
rotateMatrix(mat);
return 0;
}
|
constant
|
quadratic
|
// C++ program for left rotation of matrix by 180
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
// Function to rotate the matrix by 180 degree
void reverseColumns(int arr[R][C])
{
for (int i = 0; i < C; i++)
for (int j = 0, k = C - 1; j < k; j++, k--)
swap(arr[j][i], arr[k][i]);
}
// Function for transpose of matrix
void transpose(int arr[R][C])
{
for (int i = 0; i < R; i++)
for (int j = i; j < C; j++)
swap(arr[i][j], arr[j][i]);
}
// Function for display the matrix
void printMatrix(int arr[R][C])
{
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++)
cout << arr[i][j] << " ";
cout << '\n';
}
}
// Function to anticlockwise rotate matrix
// by 180 degree
void rotate180(int arr[R][C])
{
transpose(arr);
reverseColumns(arr);
transpose(arr);
reverseColumns(arr);
}
// Driven code
int main()
{
int arr[R][C] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotate180(arr);
printMatrix(arr);
return 0;
}
|
constant
|
quadratic
|
#include <bits/stdc++.h>
using namespace std;
/**
* Reverse Row at specified index in the matrix
* @param data matrix
* @param index row index
*/
void reverseRow(vector<vector<int>>& data,
int index)
{
int cols = data[index].size();
for(int i = 0; i < cols / 2; i++)
{
int temp = data[index][i];
data[index][i] = data[index][cols - i - 1];
data[index][cols - i - 1] = temp;
}
}
/**
* Print Matrix data
* @param data matrix
*/
void printMatrix(vector<vector<int>>& data)
{
for(int i = 0; i < data.size(); i++)
{
for(int j = 0; j < data[i].size(); j++)
{
cout << data[i][j] << " ";
}
cout << endl;
}
}
/**
* Rotate Matrix by 180 degrees
* @param data matrix
*/
void rotateMatrix180(vector<vector<int>>& data)
{
int rows = data.size();
int cols = data[0].size();
if (rows % 2 != 0)
{
// If N is odd reverse the middle
// row in the matrix
reverseRow(data, data.size() / 2);
}
// Swap the value of matrix [i][j] with
// [rows - i - 1][cols - j - 1] for half
// the rows size.
for(int i = 0; i <= (rows/2) - 1; i++)
{
for(int j = 0; j < cols; j++)
{
int temp = data[i][j];
data[i][j] = data[rows - i - 1][cols - j - 1];
data[rows - i - 1][cols - j - 1] = temp;
}
}
}
// Driver code
int main()
{
vector<vector<int>> data{ { 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 },
{ 16, 17, 18, 19, 20 },
{ 21, 22, 23, 24, 25 } };
// Rotate Matrix
rotateMatrix180(data);
// Print Matrix
printMatrix(data);
return 0;
}
// This code is contributed by divyeshrabadiya07
|
constant
|
quadratic
|
// C++ program to rotate individual rings by k in
// spiral order traversal.
#include<bits/stdc++.h>
#define MAX 100
using namespace std;
// Fills temp array into mat[][] using spiral order
// traversal.
void fillSpiral(int mat[][MAX], int m, int n, int temp[])
{
int i, k = 0, l = 0;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index */
int tIdx = 0; // Index in temp array
while (k < m && l < n)
{
/* first row from the remaining rows */
for (int i = l; i < n; ++i)
mat[k][i] = temp[tIdx++];
k++;
/* last column from the remaining columns */
for (int i = k; i < m; ++i)
mat[i][n-1] = temp[tIdx++];
n--;
/* last row from the remaining rows */
if (k < m)
{
for (int i = n-1; i >= l; --i)
mat[m-1][i] = temp[tIdx++];
m--;
}
/* first column from the remaining columns */
if (l < n)
{
for (int i = m-1; i >= k; --i)
mat[i][l] = temp[tIdx++];
l++;
}
}
}
// Function to spirally traverse matrix and
// rotate each ring of matrix by K elements
// mat[][] --> matrix of elements
// M --> number of rows
// N --> number of columns
void spiralRotate(int mat[][MAX], int M, int N, int k)
{
// Create a temporary array to store the result
int temp[M*N];
/* s - starting row index
m - ending row index
l - starting column index
n - ending column index; */
int m = M, n = N, s = 0, l = 0;
int *start = temp; // Start position of current ring
int tIdx = 0; // Index in temp
while (s < m && l < n)
{
// Initialize end position of current ring
int *end = start;
// copy the first row from the remaining rows
for (int i = l; i < n; ++i)
{
temp[tIdx++] = mat[s][i];
end++;
}
s++;
// copy the last column from the remaining columns
for (int i = s; i < m; ++i)
{
temp[tIdx++] = mat[i][n-1];
end++;
}
n--;
// copy the last row from the remaining rows
if (s < m)
{
for (int i = n-1; i >= l; --i)
{
temp[tIdx++] = mat[m-1][i];
end++;
}
m--;
}
/* copy the first column from the remaining columns */
if (l < n)
{
for (int i = m-1; i >= s; --i)
{
temp[tIdx++] = mat[i][l];
end++;
}
l++;
}
// if elements in current ring greater than
// k then rotate elements of current ring
if (end-start > k)
{
// Rotate current ring using reversal
// algorithm for rotation
reverse(start, start+k);
reverse(start+k, end);
reverse(start, end);
// Reset start for next ring
start = end;
}
}
// Fill temp array in original matrix.
fillSpiral(mat, M, N, temp);
}
// Driver program to run the case
int main()
{
// Your C++ Code
int M = 4, N = 4, k = 3;
int mat[][MAX]= {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
spiralRotate(mat, M, N, k);
// print modified matrix
for (int i=0; i<M; i++)
{
for (int j=0; j<N; j++)
cout << mat[i][j] << " ";
cout << endl;
}
return 0;
}
|
quadratic
|
quadratic
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.