Linked List
Linked List
Linked List
The content of this book comes from geeksforgeeks.org and it's licensed under Creative
Commons Attribution-NonCommercial-NoDerivs 2.5 India
Made by Jing. 2015.
Updated on September 30, 2015
Head over to this github repo to report issues or contribute.
Algorithm:
1. Initialize count = 0
2. Loop through the link list
a. if count is equal to the passed index then return current
node
b. Increment count
c. change current to point to next of the current.
Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
Source
http://www.geeksforgeeks.org/write-a-function-to-get-nth-node-in-a-linked-list/
Category: Linked Lists Tags: GetNth, Linked Lists
Program:
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
This solution doesn’t work if the node to be deleted is the last node of the list. To
make this solution work we can mark the end node as a dummy node. But the
programs/functions that are using this function should also be modified.
You can try this problem for doubly linked list.
Source
http://www.geeksforgeeks.org/given-only-a-pointer-to-a-node-to-be-deleted-in-a-singly-
linked-list-how-do-you-delete-it/
Category: Linked Lists Tags: Linked Lists, loop
Method 2:
Traverse linked list using two pointers. Move one pointer by one and other pointer by two.
When the fast pointer reaches end slow pointer will reach middle of the linked list.
#include<stdio.h>
#include<stdlib.h>
if (head!=NULL)
{
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
printf("The middle element is [%d]\n\n", slow_ptr->data);
}
}
return 0;
}
Output:
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Method 3:
Initialize mid element as head and initialize a counter as 0. Traverse the list from head,
while traversing increment the counter and change mid to mid->next whenever the
counter is odd. So the mid will move only half of the total length of the list.
Thanks to Narendra Kangralkar for suggesting this method.
#include<stdio.h>
#include<stdlib.h>
++count;
head = head->next;
}
return 0;
}
Output:
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Source
http://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/
Category: Linked Lists
Nth node from the end of a Linked List
Given a Linked List and a number n, write a function that returns the value at the nth node
from end of the Linked List.
Method 1 (Use length of linked list)
1) Calculate the length of Linked List. Let the length be len.
2) Print the (len – n + 1)th node from the begining of the Linked List.
#include<stdio.h>
#include<stdlib.h>
/* 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;
temp = head;
return;
}
printNthFromLast(head, 5);
getchar();
return 0;
}
Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing
following code.
#include<stdio.h>
#include<stdlib.h>
/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct node *head, int n)
{
struct node *main_ptr = head;
struct node *ref_ptr = head;
int count = 0;
if(head != NULL)
{
while( count < n )
{
if(ref_ptr == NULL)
{
printf("%d is greater than the no. of "
"nodes in list", n);
return;
}
ref_ptr = ref_ptr->next;
count++;
} /* End of while*/
while(ref_ptr != NULL)
{
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
printf("Node no. %d from last is %d ",
n, main_ptr->data);
}
}
printNthFromLast(head, 3);
getchar();
}
Source
http://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
Category: Linked Lists Tags: Linked Lists
Write a function to delete a Linked List
Algorithm: Iterate through the linked list and delete all the nodes one by one. Main point
here is not to access next of the current pointer if current pointer is deleted.
Implementation:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
Source
http://www.geeksforgeeks.org/write-a-function-to-delete-a-linked-list/
Category: Linked Lists Tags: Delete a Linked List, Linked Lists
Write a function that counts the number of times a given int occurs in
a Linked List
Here is a solution.
Algorithm:
Implementation:
#include<stdio.h>
#include<stdlib.h>
Source
http://www.geeksforgeeks.org/write-a-function-that-counts-the-number-of-times-a-
given-int-occurs-in-a-linked-list/
Category: Linked Lists Tags: Linked Lists
Program:
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
This solution doesn’t work if the node to be deleted is the last node of the list. To
make this solution work we can mark the end node as a dummy node. But the
programs/functions that are using this function should also be modified.
Try this problem for doubly linked list.
Source
http://www.geeksforgeeks.org/in-a-linked-list-given-only-a-pointer-to-a-node-to-be-
deleted-in-a-singly-linked-list-how-do-you-delete-it/
Category: Linked Lists
#include<stdio.h>
#include<stdlib.h>
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
printList(head);
reverse(&head);
printf("\n Reversed Linked list \n");
printList(head);
getchar();
}
Recursive Method:
1) Divide the list in two parts - first node and rest of the linked list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) Fix head pointer
/* empty list */
if (*head_ref == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
struct node
{
int data;
struct node *next;
};
Output:
Given linked list
1 2 2 4 5 6 7 8
Source
http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/
Category: Linked Lists
#include<stdio.h>
#include<stdlib.h>
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 10);
getchar();
}
Time Complexity: O(n)
Auxiliary Space: O(1)
References:
http://en.wikipedia.org/wiki/Cycle_detection
http://ostermiller.org/find_loop_singly_linked_list.html
Source
http://www.geeksforgeeks.org/write-a-c-function-to-detect-loop-in-a-linked-list/
Category: Linked Lists Tags: Linked Lists, loop
// Now reverse the second half and compare it with first half
second_half = slow_ptr;
prev_of_slow_ptr->next = NULL; // NULL terminate first half
reverse(&second_half); // Reverse the second half
res = compareLists(head, second_half); // compare
return 0;
}
Output:
a->NULL
Palindrome
b->a->NULL
Not Palindrome
a->b->a->NULL
Is Palindrome
c->a->b->a->NULL
Not Palindrome
a->c->a->b->a->NULL
Not Palindrome
b->a->c->a->b->a->NULL
Not Palindrome
a->b->a->c->a->b->a->NULL
Is Palindrome
Time Complexity O(n)
Auxiliary Space: O(1)
return isp1;
}
return 0;
}
Output:
a->NULL
Not Palindrome
b->a->NULL
Not Palindrome
a->b->a->NULL
Is Palindrome
c->a->b->a->NULL
Not Palindrome
a->c->a->b->a->NULL
Not Palindrome
b->a->c->a->b->a->NULL
Not Palindrome
a->b->a->c->a->b->a->NULL
Is Palindrome
Source
http://www.geeksforgeeks.org/the-great-tree-list-recursion-problem/
Category: Linked Lists Trees
Figure 2
4) Change the arbit pointer of all nodes in copy linked list to point to corresponding node in
original linked list.
5) Now construct the arbit pointer in copy linked list as below and restore the next pointer
of nodes in the original linked list.
copy_list_node->arbit =
copy_list_node->arbit->arbit->next;
copy_list_node = copy_list_node->next;
6) Restore the next pointers in original linked list from the stored mappings(in step 2).
Time Complexity: O(n)
Auxiliary Space: O(n)
This works because original->next is nothing but copy of original and Original->arbitrary-
>next is nothing but copy of arbitrary.
3) Now restore the original and copy linked lists in this fashion in a single loop.
original->next = original->next->next;
copy->next = copy->next->next;
Source
http://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/
Memory efficient doubly linked list
Asked by Varun Bhatia.
Question:
Write a code for implementation of doubly linked list with use of single pointer in each
node.
Solution:
This question is solved and very well explained at
http://www.linuxjournal.com/article/6828.
We also recommend to read http://en.wikipedia.org/wiki/XOR_linked_list
Source
http://www.geeksforgeeks.org/memory-efficient-doubly-linked-list/
Category: Linked Lists
Given a linked list which is sorted, how will you insert in sorted way
Algorithm:
Let input linked list is sorted in increasing order.
1) If Linked list is empty then make the node as head and return it.
2) If value of the node to be inserted is smaller than value of head node
then insert the node at start and make it head.
3) In a loop, find the appropriate node after which the input node (let 9) is
to be inserted. To find the appropriate node start from head, keep moving
until you reach a node GN (10 in the below diagram) who's value is
greater than the input node. The node just before GN is the appropriate
node (7).
4) Insert the node (9) after the appropriate node (7) found in step 3.
Implementation:
return new_node;
}
getchar();
return 0;
}
Shorter Implementation using double pointers
Thanks to Murat M Ozturk for providing this solution. Please see Murat M Ozturk’s
comment below for complete function. The code uses double pointer to keep track of the
next pointer of the previous node (after which new node is being inserted).
Note that below line in code changes current to have address of next pointer in a node.
current = &((*current)->next);
Source
http://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-
in-sorted-way/
Category: Linked Lists
#include<stdio.h>
#include<stdlib.h>
return -1;
}
return count;
}
1st 3->6->9->15->30
2nd 10->15->30
head1->next->next->next = NULL;
getchar();
}
1) Let X be the length of the first linked list until intersection point.
Let Y be the length of the second linked list until the intersection
point.
Let Z be the length of the linked list from intersection point to End of
the linked list including the intersection node.
We Have
X + Z = C1;
Y + Z = C2;
2) Reverse first linked list.
3) Traverse Second linked list. Let C3 be the length of second list - 1.
Now we have
X + Y = C3
We have 3 linear equations. By solving them, we get
X = (C1 + C3 – C2)/2;
Y = (C2 + C3 – C1)/2;
Z = (C1 + C2 – C3)/2;
WE GOT THE INTERSECTION POINT.
4) Reverse first linked list.
Time complexity of this method is O(m+n) and used Auxiliary space is O(1)
Please write comments if you find any bug in the above algorithm or a better way to solve
the same problem.
Source
http://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-
linked-lists/
printReverse(head)
1. call print reverse for hed->next
2. print head->data
Implementation:
#include<stdio.h>
#include<stdlib.h>
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 4);
printReverse(head);
getchar();
}
Source
http://www.geeksforgeeks.org/write-a-recursive-function-to-print-reverse-of-a-linked-
list/
Category: Linked Lists
Remove duplicates from a sorted linked list
Write a removeDuplicates() function which takes a list sorted in non-decreasing order and
deletes any duplicate nodes from the list. The list should only be traversed once.
For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates()
should convert the list to 11->21->43->60.
Algorithm:
Traverse the list from the head (or start) node. While traversing, compare each node with
its next node. If data of next node is same as current node then delete the next node. Before
we delete a node, we need to store next pointer of the node
Implementation:
Functions other than removeDuplicates() are just to create a linked linked list and test
removeDuplicates().
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging 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));
getchar();
}
Time Complexity: O(n) where n is number of nodes in the given linked list.
References:
cslibrary.stanford.edu/105/LinkedListProblems.pdf
Source
http://www.geeksforgeeks.org/remove-duplicates-from-a-sorted-linked-list/
Category: Linked Lists
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct node** head_ref, int new_data);
removeDuplicates(start);
getchar();
}
Please note that this method doesn’t preserve the original order of elements.
Time Complexity: O(nLogn)
METHOD 3 (Use Hashing)
We traverse the link list from head to end. For every newly encountered element, we check
whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table.
Thanks to bearwang for suggesting this method.
Time Complexity: O(n) on average (assuming that hash table access time is O(1) on
average).
Please write comments if you find any of the above explanations/algorithms incorrect, or a
better ways to solve the same problem.
Source
http://www.geeksforgeeks.org/remove-duplicates-from-an-unsorted-linked-list/
Category: Linked Lists
Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev
and next pointers for all nodes, change prev of the head (or start) and change the head
pointer in the end.
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging 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));
getchar();
}
Source
http://www.geeksforgeeks.org/reverse-a-doubly-linked-list/
Category: Linked Lists
if(head == NULL)
return;
/* UTILITY FUNCTIONS */
/* Function to insert a node at the begining of a Circular
linked lsit */
void push(struct node **head_ref, int data)
{
struct node *ptr1 = (struct node *)malloc(sizeof(struct node));
struct node *temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
*head_ref = ptr1;
}
getchar();
return 0;
}
Source
http://www.geeksforgeeks.org/split-a-circular-linked-list-into-two-halves/
Category: Linked Lists
struct node
{
int data;
struct node *next;
};
fun1(head->next);
printf("%d ", head->data);
}
fun1() prints the given Linked List in reverse manner. For Linked List 1->2->3->4->5,
fun1() prints 5->4->3->2->1.
if(head->next != NULL )
fun2(head->next->next);
printf("%d ", head->data);
}
fun2() prints alternate nodes of the given Linked List, first from head to end, and then from
end to head. If Linked List has even number of nodes, then fun2() skips the last node. For
Linked List 1->2->3->4->5, fun2() prints 1 3 5 5 3 1. For Linked List 1->2->3->4->5->6,
fun2() prints 1 3 5 5 3 1.
Below is a complete running program to test above functions.
#include<stdio.h>
#include<stdlib.h>
fun1(head->next);
printf("%d ", head->data);
}
if(start->next != NULL )
fun2(start->next->next);
printf("%d ", start->data);
}
getchar();
return 0;
}
Please write comments if you find any of the answers/explanations incorrect, or you want
to share more information about the topics discussed above.
Source
http://www.geeksforgeeks.org/practice-questions-for-linked-list-and-recursion/
Category: Linked Lists Tags: Recursion
/* UTILITY FUNCTIONS */
/* Function to add a node at the begining of Linked List */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
moveToFront(&start);
getchar();
}
Time Complexity: O(n) where n is the number of nodes in the given Linked List.
Please write comments if you find any bug in above code/algorithm, or find other ways to
solve the same problem.
Source
http://www.geeksforgeeks.org/move-last-element-to-front-of-a-given-linked-list/
Category: Linked Lists
/* UTILITY FUNCTIONS */
/* Function to swap two integers */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
pairWiseSwap(start);
getchar();
return 0;
}
Algorithm
Let the node to be deleted is del.
1) If node to be deleted is head node, then change the head pointer to next current head.
2) Set next of previous to del, if previous to del exixts.
3) Set prev of next to del, if next to del exixts.
#include <stdio.h>
#include <stdlib.h>
/* UTILITY FUNCTIONS */
/* 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));
getchar();
}
Source
http://www.geeksforgeeks.org/delete-a-node-in-a-doubly-linked-list/
Category: Linked Lists
#include<stdio.h>
#include<stdlib.h>
/*This solution uses the temporary dummy to build up the result list */
struct node* sortedIntersect(struct node* a, struct node* b)
{
struct node dummy;
struct node* tail = &dummy;
dummy.next = NULL;
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging 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));
/* 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);
getchar();
}
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
#include<stdio.h>
#include<stdlib.h>
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging 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));
/* 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);
getchar();
}
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
Method 3 (Recursive)
Below is the recursive implementation of sortedIntersect().
#include<stdio.h>
#include<stdlib.h>
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging 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));
/* 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);
return 0;
}
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
Please write comments if you find the above codes/algorithms incorrect, or find better
ways to solve the same problem.
References:
cslibrary.stanford.edu/105/LinkedListProblems.pdf
Source
http://www.geeksforgeeks.org/intersection-of-two-sorted-linked-lists/
Category: Linked Lists
Post navigation
← Maximum width of a binary tree How are variables scoped in C – Static or Dynamic? →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
#include<stdio.h>
#include<stdlib.h>
/* Free memory */
free(node);
getchar();
return 0;
}
Time Complexity: O(n) where n is the number of nodes in the given Linked List.
Method 2 (Recursive)
Recursive code uses the same approach as method 1. The recursive coed is simple and
short, but causes O(n) recursive function calls for a linked list of size n.
if (node == NULL)
return;
/* pull off the front node of the source and put it in dest */
void MoveNode(struct node** destRef, struct node** sourceRef) ;
/* Given the source list, split its nodes into two shorter lists.
If we number the elements 0, 1, 2, ... then all the even elements
should go in the first list, and all the odd elements in the second.
The elements in the new lists may be in any order. */
void AlternatingSplit(struct node* source, struct node** aRef,
struct node** bRef)
{
/* split the nodes of source to these 'a' and 'b' lists */
struct node* a = NULL;
struct node* b = NULL;
/* Take the node from the front of the source, and move it to the front of
the dest.
It is an error to call this with the source list empty.
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging 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));
getchar();
return 0;
}
Time Complexity: O(n) where n is number of node in the given linked list.
Time Complexity: O(n) where n is number of node in the given linked list.
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
Please write comments if you find the above code/algorithm incorrect, or find better ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/alternating-split-of-a-given-singly-linked-list/
Category: Linked Lists
Post navigation
← Delete alternate nodes of a Linked List Output of C Programs | Set 14 →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
/* pull off the front node of the source and put it in dest */
void MoveNode(struct node** destRef, struct node** sourceRef);
/* Takes two lists sorted in increasing order, and splices their nodes
together to make one big sorted list which is returned. */
struct node* SortedMerge(struct node* a, struct node* b)
{
/* a dummy first node to hang the result on */
struct node dummy;
/* UTILITY FUNCTIONS */
/*MoveNode() function takes the node from the front of the source, and move
it to the front of the dest.
It is an error to call this with the source list empty.
push(&b, 20);
push(&b, 3);
push(&b, 2);
getchar();
return 0;
}
while(1)
{
if (a == NULL)
{
*lastPtrRef = b;
break;
}
else if (b==NULL)
{
*lastPtrRef = a;
break;
}
if(a->data <= b->data)
{
MoveNode(lastPtrRef, &a);
}
else
{
MoveNode(lastPtrRef, &b);
}
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
/* Pick either a or b, and recur */
if (a->data <= b->data)
{
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return(result);
}
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
Please write comments if you find the above code/algorithm incorrect, or find better ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/merge-two-sorted-linked-lists/
Category: Linked Lists
Post navigation
← Total number of possible Binary Search Trees with n keys A nested loop puzzle →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
#include<stdio.h>
#include<stdlib.h>
push(&b, 1);
push(&b, 2);
push(&b, 3);
if(areIdentical(a, b) == 1)
printf(" Linked Lists are identical ");
else
printf(" Linked Lists are not identical ");
getchar();
return 0;
}
Method 2 (Recursive)
Recursive solution code is much cleaner than the iterative code. You probably wouldn’t
want to use the recursive version for production code however, because it will use stack
space which is proportional to the length of the lists
Time Complexity: O(n) for both iterative and recursive versions. n is the length of the
smaller list among a and b.
Please write comments if you find the above codes/algorithms incorrect, or find better
ways to solve the same problem.
Source
http://www.geeksforgeeks.org/identical-linked-lists/
Category: Linked Lists
MergeSort(headRef)
1) If head is NULL or there is only one element in the Linked List
then return.
2) Else divide the linked list into two halves.
FrontBackSplit(head, &a, &b); /* a and b are two halves */
3) Sort the two halves a and b.
MergeSort(a);
MergeSort(b);
4) Merge the sorted a and b (using SortedMerge() discussed here)
and update the head pointer using headRef.
*headRef = SortedMerge(a, b);
#include<stdio.h>
#include<stdlib.h>
/* function prototypes */
struct node* SortedMerge(struct node* a, struct node* b);
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef);
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
/* UTILITY FUNCTIONS */
/* Split the nodes of the given list into front and back halves,
and return the two lists using the reference parameters.
If the length is odd, the extra node should go in the front list.
Uses the fast/slow pointer strategy. */
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef)
{
struct node* fast;
struct node* slow;
if (source==NULL || source->next==NULL)
{
/* length < 2 cases */
*frontRef = source;
*backRef = NULL;
}
else
{
slow = source;
fast = source->next;
getchar();
return 0;
}
Source
http://www.geeksforgeeks.org/merge-sort-for-linked-list/
Category: Linked Lists
Post navigation
← Identical Linked Lists Segregate Even and Odd numbers →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
Example:
Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3
Output: 3->2->1->6->5->4->8->7->NULL.
Algorithm: reverse(head, k)
1) Reverse the first sub-list of size k. While reversing keep track of the next node and
previous node. Let the pointer to the next node be next and pointer to the previous node be
prev. See this post for reversing a linked list.
2) head->next = reverse(next, k) /* Recursively call for rest of the list and link the two sub-
lists */
3) return prev /* prev becomes the new head of the list (see the diagrams of iterative
method of this post) */
#include<stdio.h>
#include<stdlib.h>
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
Time Complexity: O(n) where n is the number of nodes in the given list.
Please write comments if you find the above code/algorithm incorrect, or find other ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/
Category: Linked Lists
Source
http://www.geeksforgeeks.org/linked-list-vs-array/
Algorithm:
Allocate memory for the newly inserted node and put data in the newly allocated node. Let
the pointer to the new node be new_node. After memory allocation, following are the three
cases that need to be handled.
#include<stdio.h>
#include<stdlib.h>
new_node->next = current->next;
current->next = new_node;
}
}
if(start != NULL)
{
temp = start;
printf("\n");
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != start);
}
}
printList(start);
getchar();
return 0;
}
Output:
1 2 11 12 56 90
Time Complexity: O(n) where n is the number of nodes in the given linked list.
Case 2 of the above algorithm/code can be optimized. Please see thiscomment from Pavan.
To implement the suggested change we need to modify the case 2 to following.
new_node->next = (*head_ref)->next;
(*head_ref)->next = new_node;
}
Please write comments if you find the above code/algorithm incorrect, or find other ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/sorted-insert-for-circular-linked-list/
Category: Linked Lists
Reverse alternate K nodes in a Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input
to the function) in an efficient way. Give the complexity of your algorithm.
Example:
Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3
Output: 3->2->1->4->5->6->9->8->7->NULL.
Method 1 (Process 2k nodes and recursively call for rest of the list)
This method is basically an extension of the method discussed in thispost.
#include<stdio.h>
#include<stdlib.h>
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
getchar();
return(0);
}
Output:
Given linked list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Modified Linked list
3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19
Time Complexity: O(n)
Method 2 (Process k nodes and recursively call for rest of the list)
The method 1 reverses the first k node and then moves the pointer to k nodes ahead. So
method 1 uses two while loops and processes 2k nodes in one recursive call.
This method processes only k nodes in a recursive call. It uses a third bool parameter b
which decides whether to reverse the k elements or simply move the pointer.
#include<stdio.h>
#include<stdlib.h>
int count = 1;
struct node *prev = NULL;
struct node *current = node;
struct node *next;
prev = current;
current = next;
count++;
}
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
getchar();
return(0);
}
Output:
Given linked list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Modified Linked list
3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19
Time Complexity: O(n)
Source:
http://geeksforgeeks.org/forum/topic/amazon-interview-question-2
Please write comments if you find the above code/algorithm incorrect, or find other ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/
Category: Linked Lists
Post navigation
← Program to count number of set bits in an (big) array Next Greater Element →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
#include <stdio.h>
#include <stdlib.h>
/* Initialize max */
struct node *maxnode = head;
struct node *temp;
}
}
delLesserNodes(&head);
getchar();
return 0;
}
Output:
Source:
http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-
engineerdeveloper-about-linked-lists-6
Please write comments if you find the above code/algorithm incorrect, or find other ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/delete-nodes-which-have-a-greater-value-on-right-side/
#include <stdio.h>
#include <stdlib.h>
// 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;
/* 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 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));
push(&head, 11);
push(&head, 10);
push(&head, 8);
push(&head, 6);
push(&head, 4);
push(&head, 2);
push(&head, 0);
segregateEvenOdd(&head);
return 0;
}
Output:
/* If ptr2 did't reach ptr1 then try the next node after ptr1 */
else
ptr1 = ptr1->next;
}
/* After the end of loop ptr2 is the last node of the loop. So
make next of ptr2 as NULL */
ptr2->next = NULL;
}
/* UTILITY FUNCTIONS */
/* Given a reference (pointer to pointer) to the head
of a list and an int, pushes 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));
push(&head, 10);
push(&head, 4);
push(&head, 15);
push(&head, 20);
push(&head, 50);
detectAndRemoveLoop(head);
getchar();
return 0;
}
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* UTILITY FUNCTIONS */
/* Given a reference (pointer to pointer) to the head
of a list and an int, pushes 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));
push(&head, 10);
push(&head, 4);
push(&head, 15);
push(&head, 20);
push(&head, 50);
detectAndRemoveLoop(head);
getchar();
return 0;
}
Please write comments if you find the above codes/algorithms incorrect, or find other ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
Category: Linked Lists
Post navigation
← Check if a given Binary Tree is SumTree Interpolation search vs Binary search →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
Consider the above Doubly Linked List. Following are the Ordinary and XOR (or Memory
Effiecient) representations of the Doubly Linked List.
Ordinary Representation:
Node A:
prev = NULL, next = add(B) // previous is NULL and next is address of B
Node B:
prev = add(A), next = add(C) // previous is address of A and next is address of C
Node C:
prev = add(B), next = add(D) // previous is address of B and next is address of D
Node D:
prev = add(C), next = NULL // previous is address of C and next is NULL
XOR List Representation:
Let us call the address variable in XOR representation npx (XOR of next and previous)
Node A:
npx = 0 XOR add(B) // bitwise XOR of zero and address of B
Node B:
npx = add(A) XOR add(C) // bitwise XOR of address of A and address of C
Node C:
npx = add(B) XOR add(D) // bitwise XOR of address of B and address of D
Node D:
npx = add(C) XOR 0 // bitwise XOR of address of C and 0
Traversal of XOR Linked List:
We can traverse the XOR list in both forward and reverse direction. While traversing the
list we need to remember the address of the previously accessed node in order to calculate
the next node’s address. For example when we are at node C, we must have address of B.
XOR of add(B) and npx of C gives us the add(D). The reason is simple: npx(C) is “add(B)
XOR add(D)”. If we do xor of npx(C) with add(B), we get the result as “add(B) XOR add(D)
XOR add(B)” which is “add(D) XOR 0″ which is “add(D)”. So we have the address of next
node. Similarly we can traverse the list in backward direction.
We have covered more on XOR Linked List in the following post.
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
References:
http://en.wikipedia.org/wiki/XOR_linked_list
http://www.linuxjournal.com/article/6828?page=0,0
Source
http://www.geeksforgeeks.org/xor-linked-list-a-memory-efficient-doubly-linked-list-set-
1/
Input:
First List: 5->6->3 // represents number 365
Second List: 8->4->2 // represents number 248
Output
Resultant list: 3->1->6 // represents number 613
Example 2
Input:
First List: 7->5->9->4->6 // represents number 64957
Second List: 8->4 // represents number 48
Output
Resultant list: 5->0->0->5->6 // represents number 65005
Solution
Traverse both lists. One by one pick nodes of both lists and add the values. If sum is more
than 10 then make carry as 1 and reduce sum. If one list has more elements than the other
then consider remaining values of this list as 0. Following is C implementation of this
approach.
#include<stdio.h>
#include<stdlib.h>
/* Adds contents of two linked lists and return the head node of resultant
list */
struct node* addTwoLists (struct node* first, struct node* second)
{
struct node* res = NULL; // res is head node of the resultant list
struct node *temp, *prev = NULL;
int carry = 0, sum;
if (carry > 0)
temp->next = newNode(carry);
return 0;
}
Output:
First List is 7 5 9 4 6
Second List is 8 4
Resultant list is 5 0 0 5 6
Time Complexity: O(m + n) where m and n are number of nodes in first and second lists
respectively.
Please write comments if you find the above codes/algorithms incorrect, or find other ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists/
Category: Linked Lists
2) Functions that modify the head pointer: Examples include, inserting a node at the
beginning (head pointer is always modified in this function), inserting a node at the end
(head pointer is modified only when the first node is being inserted), deleting a given node
(head pointer is modified when the deleted node is first node). There may be different
ways to update the head pointer in these functions. Let us discuss these ways using
following simple problem:
“Given a linked list, write a function deleteFirst() that deletes the first node of a given linked
list. For example, if the list is 1->2->3->4, then it should be modified to 2->3->4″
Algorithm to solve the problem is a simple 3 step process: (a) Store the head pointer (b)
change the head pointer to point to next node (c) delete the previous head node.
Following are different ways to update head pointer in deleteFirst() so that the list is
updated everywhere.
2.1) Make head pointer global: We can make the head pointer global so that it can be
accessed and updated in our function. Following is C code that uses global head pointer.
// global head pointer
struct node *head = NULL;
2.2) Return head pointer: We can write deleteFirst() in such a way that it returns the
modified head pointer. Whoever is using this function, have to use the returned value to
update the head node.
return head;
}
2.3) Use Double Pointer: This approach follows the simple C rule: if you want to modify
local variable of one function inside another function, pass pointer to that variable. So we can
pass pointer to the head pointer to modify the head pointer in our deleteFirst() function.
#include <stdio.h>
#include <stdlib.h>
// free memory
free(n);
return;
}
// Free memory
free(n);
return;
}
getchar();
return 0;
}
Output:
Please write comments if you find the above codes/algorithms incorrect, or find other ways
to solve the same problem.
Source
http://www.geeksforgeeks.org/delete-a-given-node-in-linked-list-under-given-
constraints/
Category: Linked Lists
Method 1 (Simple)
Following is a simple algorithm where we first find the middle node of list and make it root
of the tree to be constructed.
#include<stdio.h>
#include<stdlib.h>
/* This function counts the number of nodes in Linked List and then calls
sortedListToBSTRecur() to construct BST */
struct TNode* sortedListToBST(struct LNode *head)
{
/*Count the number of nodes in Linked List */
int n = countLNodes(head);
/* Construct BST */
return sortedListToBSTRecur(&head, n);
}
/* The main function that constructs balanced BST and returns root of it.
head_ref --> Pointer to pointer to head node of linked list
n --> No. of nodes in Linked List */
struct TNode* sortedListToBSTRecur(struct LNode **head_ref, int n)
{
/* Base Case */
if (n <= 0)
return NULL;
return root;
}
/* UTILITY FUNCTIONS */
return node;
}
return 0;
}
Source
http://www.geeksforgeeks.org/sorted-linked-list-to-balanced-bst/
Category: Linked Lists
The Doubly Linked List conversion is very much similar to this Singly Linked List problem
and the method 1 is exactly same as the method 1 ofprevious post. Method 2 is also almost
same. The only difference in method 2 is, instead of allocating new nodes for BST, we reuse
same DLL nodes. We use prev pointer as left and next pointer as right.
Method 1 (Simple)
Following is a simple algorithm where we first find the middle node of list and make it root
of the tree to be constructed.
#include<stdio.h>
#include<stdlib.h>
/* A Doubly Linked List node that will also be used as a tree node */
struct Node
{
int data;
/* This function counts the number of nodes in Linked List and then calls
sortedListToBSTRecur() to construct BST */
struct Node* sortedListToBST(struct Node *head)
{
/*Count the number of nodes in Linked List */
int n = countNodes(head);
/* Construct BST */
return sortedListToBSTRecur(&head, n);
}
/* The main function that constructs balanced BST and returns root of it.
head_ref --> Pointer to pointer to head node of Doubly linked list
n --> No. of nodes in the Doubly Linked List */
struct Node* sortedListToBSTRecur(struct Node **head_ref, int n)
{
/* Base Case */
if (n <= 0)
return NULL;
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a given Linked List */
int countNodes(struct Node *head)
{
int count = 0;
struct Node *temp = head;
while(temp)
{
temp = temp->next;
count++;
}
return count;
}
return 0;
}
Source
http://www.geeksforgeeks.org/in-place-conversion-of-sorted-dll-to-balanced-bst/
Category: Linked Lists
Input:
List1: 10->15->4->20
lsit2: 8->4->2->10
Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
Method 1 (Simple)
Following are simple algorithms to get union and intersection lists respectively.
Intersection (list1, list2)
Initialize result list as NULL. Traverse list1 and look for its each element in list2, if the
element is present in list2, then add the element to result.
Union (list1, list2):
Initialize result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in result then do not insert it to
result, otherwise insert.
This method assumes that there are no duplicates in the given lists.
Thanks to Shekhufor suggesting this method. Following is C implementation of this
method.
#include<stdio.h>
#include<stdlib.h>
// Insert those elements of list2 which are not present in result list
while (t2 != NULL)
{
if (!isPresent(result, t2->data))
push(&result, t2->data);
t2 = t2->next;
}
return result;
}
return result;
}
return 0;
}
Output:
First list is
10 15 4 20
Second list is
8 4 2 10
Intersection list is
4 10
Union list is
2 8 20 4 15 10
Time Complexity: O(mn) for both union and intersection operations. Here m is the number
of elements in first list and n is the number of elements in second list.
Method 2 (Use Merge Sort)
In this method, algorithms for Union and Intersection are very similar. First we sort the
given lists, then we traverse the sorted lists to get union and intersection.
Following are the steps to be followed to get union and intersection lists.
1) Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this
post for details of this step.
2) Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this
post for details of this step.
3) Linearly scan both sorted lists to get the union and intersection. This step takes O(m +
n) time. This step can be implemented using the same algorithm as sorted arrays algorithm
discussed here.
Time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time
complexity.
Method 3 (Use Hashing)
Union (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse both lists one by
one, for each element being visited, look the element in hash table. If the element is not
present, then insert the element to result list. If the element is present, then ignore it.
Intersection (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse list1. For each
element being visited in list1, insert the element in hash table. Traverse list2, for each
element being visited in list2, look the element in hash table. If the element is present, then
insert the element to result list. If the element is not present, then ignore it.
Both of the above methods assume that there are no duplicates.
Time complexity of this method depends on the hashing technique used and the
distribution of elements in input lists. In practical, this approach may turn out to be better
than above 2 methods.
Source: http://geeksforgeeks.org/forum/topic/union-intersection-of-unsorted-lists
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Source
http://www.geeksforgeeks.org/union-and-intersection-of-two-linked-lists/
/* Insert a node at the begining of the XORed linked list and makes the
newly inserted node as head */
void insert(struct node **head_ref, int data)
{
// Allocate memory for new node
struct node *new_node = (struct node *) malloc (sizeof (struct node) );
new_node->data = data;
/* Since new node is being inserted at the begining, npx of new node
will always be XOR of current head and NULL */
new_node->npx = XOR(*head_ref, NULL);
/* If linked list is not empty, then npx of current head node will be XOR
// Change head
*head_ref = new_node;
}
return (0);
}
Output:
Note that XOR of pointers is not defined by C/C++ standard. So the above implementation
may not work on all platforms.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above
Source
http://www.geeksforgeeks.org/xor-linked-list-a-memory-efficient-doubly-linked-list-set-
2/
Category: Linked Lists
Find a triplet from three linked lists with sum equal to a given number
Given three linked lists, say a, b and c, find one node from each list such that the sum of the
values of the nodes is equal to a given number.
For example, if the three linked lists are 12->6->29, 23->5->8 and 90->20->59, and the
given number is 101, the output should be tripel “6 5 90″.
In the following solutions, size of all three linked lists is assumed same for simplicity of
analysis. The following solutions work for linked lists of different sizes also.
A simple method to solve this problem is to run three nested loops. The outermost loop
picks an element from list a, the middle loop picks an element from b and the innermost
loop picks from c. The innermost loop also checks whether the sum of values of current
nodes of a, b and c is equal to given number. The time complexity of this method will be
O(n^3).
Sorting can be used to reduce the time complexity to O(n*n). Following are the detailed
steps.
1) Sort list b in ascending order, and list c in descending order.
2) After the b and c are sorted, one by one pick an element from list a and find the pair by
traversing both b and c. See isSumSorted() in the following code. The idea is similar to
Quadratic algorithm of 3 sum problem.
Following code implements step 2 only. The solution can be easily modified for unsorted
lists by adding the merge sort code discussed here.
#include<stdio.h>
#include<stdlib.h>
// For every node of list a, prick two nodes from lists b abd c
while (b != NULL && c != NULL)
{
// If this a triplet with given sum, print it and return true
int sum = a->data + b->data + c->data;
if (sum == givenNumber)
{
printf ("Triplet Found: %d %d %d ", a->data, b->data, c-
>data);
return true;
}
return 0;
}
Output:
Triplet Found: 15 2 8
Time complexity: The linked lists b and c can be sorted in O(nLogn) time using Merge Sort
(See this). The step 2 takes O(n*n) time. So the overall time complexity is O(nlogn) +
O(nlogn) + O(n*n) = O(n*n).
In this approach, the linked lists b and c are sorted first, so their original order will be lost.
If we want to retain the original order of b and c, we can create copy of b and c.
Source
http://www.geeksforgeeks.org/find-a-triplet-from-three-linked-lists-with-sum-equal-to-a-
given-number/
Rotate a Linked List
Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a
given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and
k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller
than the count of nodes in linked list.
To rotate the linked list, we need to change next of kth node to NULL, next of last node to
previous head node, and finally change head to (k+1)th node. So we need to get hold of
three nodes: kth node, (k+1)th node and last node.
Traverse the list from beginning and stop at kth node. Store pointer to kth node. We can
get (k+1)th node using kthNode->next. Keep traversing till end and store pointer to last
node also. Finally, change pointers as stated above.
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push (struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
return (0);
}
Output:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
Time Complexity: O(n) where n is the number of nodes in Linked List. The code traverses
the linked list only once.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Source
http://www.geeksforgeeks.org/rotate-a-linked-list/
Category: Linked Lists
Implement LRU Cache
How to implement LRU caching scheme? What data structures should be used?
We are given total possible page numbers that can be referred. We are also given cache (or
memory) size (Number of page frames that cache can hold at a time). The LRU caching
scheme is to remove the least recently used frame when the cache is full and a new page is
referenced which is not there in cache. Please see the Galvin book for more details (see the
LRU page replacement slide here).
We use two data structures to implement an LRU Cache.
1. A Queue which is implemented using a doubly linked list. The maximum size of the
queue will be equal to the total number of frames available (cache size).
The most recently used pages will be near front end and least recently pages will be near
rear end.
2. A Hash with page number as key and address of the corresponding queue node as value.
When a page is referenced, the required page may be in the memory. If it is in the memory,
we need to detach the node of the list and bring it to the front of the queue.
If the required page is not in the memory, we bring that in memory. In simple words, we
add a new node to the front of the queue and update the corresponding node address in the
hash. If the queue is full, i.e. all the frames are full, we remove a node from the rear of
queue, and add the new node to the front of queue.
Note: Initially no page is in the memory.
Below is C implementation:
return temp;
}
return queue;
}
return hash;
}
if (queue->rear)
queue->rear->next = NULL;
free( temp );
return 0;
}
Output:
5 4 1 3
Source
http://www.geeksforgeeks.org/implement-lru-cache/
Category: Linked Lists Tags: Advance Data Structures, Advanced Data Structures, Queue
Post navigation
← Microsoft Interview | Set 7 Median of two sorted arrays of different sizes →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
Write a function flatten() to flatten the lists into a single linked list. The flattened linked list
should also be sorted. For example, for the above input list, output list should be 5->7->8-
>10->19->20->22->28->30->35->40->45->50.
The idea is to use Merge() process of merge sort for linked lists. We use merge() to merge
lists one by one. We recursively merge() the current list with already flattened list.
The down pointer is used to link nodes of the flattened list.
Following is C implementation.
#include <stdio.h>
#include <stdlib.h>
return result;
}
return 0;
}
Output:
5 7 8 10 19 20 20 22 30 35 40 45 50
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Source
http://www.geeksforgeeks.org/flattening-a-linked-list/
Category: Linked Lists
Add two numbers represented by linked lists | Set 2
Given two numbers represented by two linked lists, write a function that returns sum list.
The sum list is linked list representation of addition of two input numbers. It is not allowed
to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
Example
Input:
First List: 5->6->3 // represents number 563
Second List: 8->4->2 // represents number 842
Output
Resultant list: 1->4->0->5 // represents number 1405
We have discussed a solution herewhich is for linked lists where least significant digit is
first node of lists and most significant digit is last node. In this problem, most significant
node is first node and least significant digit is last node and we are not allowed to modify
the lists. Recursion is used here to calculate sum from right to left.
Following are the steps.
1) Calculate sizes of given two linked lists.
2) If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call
stack till the rightmost node, calculate sum of rightmost nodes and forward carry to left
side.
3) If size is not same, then follow below steps:
….a) Calculate difference of sizes of two linked lists. Let the difference be diff
….b) Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate sum of
smaller list and right sub-list (of same size) of larger list. Also, store the carry of this sum.
….c) Calculate sum of the carry (calculated in previous step) with the remaining left sub-
list of larger list. Nodes of this sum are added at the beginning of sum list obtained previous
step.
Following is C implementation of the above approach.
#include <stdio.h>
#include <stdlib.h>
int sum;
return result;
}
// This function is called after the smaller list is added to the bigger
// lists's sublist of same size. Once the right sublist is added, the carry
// must be added toe left side of larger list to get the final result.
void addCarryToRemaining(node* head1, node* cur, int* carry, node** result)
{
int sum;
// The main function that adds two linked lists represented by head1 and
head2.
// The sum of two lists is stored in a list referred by result
void addList(node* head1, node* head2, node** result)
{
node *cur;
int carry = 0;
else
{
int diff = abs(size1 - size2);
printList(result);
return 0;
}
Output:
1 0 1 7
Time Complexity: O(m+n) where m and n are the sizes of given two linked lists.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Source
http://www.geeksforgeeks.org/sum-of-two-linked-lists/
Category: Linked Lists
Post navigation
← Microsoft Interview | Set 9 Output of C++ Program | Set 18 →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
int i = 0;
ptr = head;
sortList(head);
return 0;
}
Output:
Linked List Before Sorting
2 1 2 1 1 2 0 1 0
Linked List After Sorting
0 0 1 1 1 1 2 2 2
struct list
{
int data;
struct list *next;
struct list *child;
};
1) Take "cur" pointer, which will point to head of the fist level of the list
2) Take "tail" pointer, which will point to end of the first level of the
list
3) Repeat the below procedure while "curr" is not NULL.
I) if current node has a child then
a) append this new child list to the "tail"
tail->next = cur->child
b) find the last node of new child list and update "tail"
tmp = cur->child;
while (tmp->next != NULL)
tmp = tmp->next;
tail = tmp;
II) move to the next node. i.e. cur = cur->next
// A linked list node has data, next pointer and child pointer
struct node
{
int data;
struct node *next;
struct node *child;
};
int i;
for (i = 0; i < n; ++i) {
if (head == NULL)
head = p = (struct node *)malloc(sizeof(*p));
else {
p->next = (struct node *)malloc(sizeof(*p));
p = p->next;
}
p->data = arr[i];
p->next = p->child = NULL;
}
return head;
}
// This function creates the input list. The created list is same
// as shown in the above figure
struct node *createList(void)
{
int arr1[] = {10, 5, 12, 7, 11};
int arr2[] = {4, 20, 13};
int arr3[] = {17, 6};
int arr4[] = {9, 8};
int arr5[] = {19, 15};
int arr6[] = {2};
int arr7[] = {16};
int arr8[] = {3};
/* Return head pointer of first linked list. Note that all nodes are
reachable from head1 */
return head1;
}
Output:
10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15
Time Complexity: Since every node is visited at most twice, the time complexity is O(n)
where n is the number of nodes in given linked list.
This article is compiled by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
http://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/
Category: Linked Lists
Post navigation
← Microsoft Interview | 15 Iterative Postorder Traversal | Set 1 (Using Two Stacks) →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
What is the time complexity with two layers? The worst case time complexity is number
of nodes on “express lane” plus number of nodes in a segment (A segment is number of
“normal lane” nodes between two “express lane” nodes) of “normal lane”. So if we have n
nodes on “normal lane”, √n (square root of n) nodes on “express lane” and we equally
divide the “normal lane”, then there will be √n nodes in every segment of “normal lane” .
√n is actually optimal division with two layers. With this arrangement, the number of
nodes traversed for a search will be O(√n). Therefore, with O(√n) extra space, we are able
to reduce the time complexity to O(√n).
Can we do better?
The time complexity of skip lists can be reduced further by adding more layers. In fact, the
time complexity of search, insert and delete can become O(Logn) in average case. We will
soon be publishing more posts on Skip Lists.
References
MIT Video Lecture on Skip Lists
http://en.wikipedia.org/wiki/Skip_list
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Source
http://www.geeksforgeeks.org/skip-list/
/* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */
void quickSort(int A[], int l, int h)
{
if (l < h)
{
int p = partition(A, l, h); /* Partitioning index */
quickSort(A, l, p - 1);
quickSort(A, p + 1, h);
}
}
swap(&(i->data), &(j->data));
}
}
i = (i == NULL)? l : i->next; // Similar to i++
swap(&(i->data), &(h->data));
return i;
}
quickSort(a);
return 0;
}
Output :
Linked List before sorting
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
Source
http://www.geeksforgeeks.org/quicksort-for-linked-list/
Category: Linked Lists
Post navigation
← B-Tree | Set 2 (Insert) Longest prefix matching – A Trie based solution in Java →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
Swap Kth node from beginning with Kth node from end in a Linked
List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping
of data is not allowed, only pointers should be changed. This requirement may be
logical in many situations where the linked list data part is huge (For example student
details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most of
the compilers).
The problem seems simple at first look, but it has many interesting cases.
Let X be the kth node from beginning and Y be the kth node from end. Following are the
interesting cases that must be handled.
1) Y is next to X
2) X is next to Y
3) X and Y are same
4) X and Y don’t exist (k is more than number of nodes in linked list)
We strongly recommend you to try it yourself first, then see the below solution. It will be a
good exercise of pointers.
// A C++ program to swap Kth node from beginning with kth node from end
#include <iostream>
#include <stdlib.h>
using namespace std;
// 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 beginning of 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;
}
return 0;
}
Output:
Original Linked List: 1 2 3 4 5 6 7 8
Please note that the above code runs three separate loops to count nodes, find x and x prev,
and to find y and y_prev. These three things can be done in a single loop. The code uses
three loops to keep things simple and readable.
Thanks to Chandra Prakash for initial solution. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
http://www.geeksforgeeks.org/swap-kth-node-from-beginning-with-kth-node-from-end-
in-a-linked-list/
Category: Linked Lists
ms->count -= 1;
free(head);
return item;
}
return ms->mid->data;
}
Output:
Item popped is 77
Item popped is 66
Middle Element is 33
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Source
http://www.geeksforgeeks.org/design-a-stack-with-find-middle-operation/
Category: Linked Lists Tags: stack
Input:
M = 2, N = 2
Linked List: 1->2->3->4->5->6->7->8
Output:
Linked List: 1->2->5->6
Input:
M = 3, N = 2
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->2->3->6->7->8
Input:
M = 1, N = 1
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->3->5->7->9
The main part of the problem is to maintain proper links between nodes, make sure that all
corner cases are handled. Following is C implementation of function skipMdeleteN() that
skips M nodes and delete N nodes till end of list. It is assumed that M cannot be 0.
// Function to skip M nodes and then delete N nodes of the linked list.
void skipMdeleteN(struct node *head, int M, int N)
{
struct node *curr = head, *t;
int count;
skipMdeleteN(head, M, N);
return 0;
}
Output:
M = 2, N = 3
Given Linked list is :
1 2 3 4 5 6 7 8 9 10
Source
http://www.geeksforgeeks.org/delete-n-nodes-after-m-nodes-of-a-linked-list/
Category: Linked Lists
// 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;
}
}
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;
}
quickSort(&a);
Output:
Linked List before sorting
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
Source
http://www.geeksforgeeks.org/quicksort-on-singly-linked-list/
Category: Linked Lists
Post navigation
← [TopTalent.in] Interview with Manpreet Who Got Offers From Amazon, Hoppr,
Browserstack, Reliance via TopTalent.in Print all possible strings of length k that can be
formed from a set of n characters →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
push(&q, 8);
push(&q, 7);
push(&q, 6);
push(&q, 5);
push(&q, 4);
printf("Second Linked List:\n");
printList(q);
merge(p, &q);
getchar();
return 0;
}
Output:
First Linked List:
1 2 3
Second Linked List:
4 5 6 7 8
Modified First Linked List:
1 4 2 5 3 6
Modified Second Linked List:
7 8
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
http://www.geeksforgeeks.org/merge-a-linked-list-into-another-linked-list-at-alternate-
positions/
Category: Linked Lists
Source
http://www.geeksforgeeks.org/self-organizing-list-set-1-introduction/
/* This program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls. */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
pairWiseSwap(&start);
Output:
Time Complexity: Time complexity of the above program is O(n) where n is the number of
nodes in a given linked list. The while loop does a traversal of the given linked list.
Following is recursive implementation of the same approach. We change first two nodes
and recur for the remaining list. Thanks to geek and omer salem for suggesting this
method.
/* This program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls. */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
// Change head
struct node* newhead = head->next;
// Change next of second node
head->next->next = head;
return 0;
}
This article is contributed by Gautam Kumar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
http://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list-by-
changing-links/
Category: Linked Lists Tags: Linked Lists
Given a linked list, reverse alternate nodes and append at the end
Given a linked list, reverse alternate nodes and append them to end of list. Extra allowed
space is O(1)
Examples
We strongly recommend to minimize the browser and try this yourself first.
The idea is to maintain two linked lists, one list of all odd positioned nodes (1, 3, 5 in above
example) and other list of all even positioned nodes (6, 4 and 2 in above example).
Following are detailed steps.
1) Traverse the given linked list which is considered as odd list. Do following for every
visited node.
……a) If the node is even node, remove it from odd list and add it to the front of even node
list. Nodes are added at front to keep the reverse order.
2) Append the even node list at the end of odd node list.
#include<stdio.h>
#include<stdlib.h>
/* Function to reverse all even positioned node and append at the end
odd is the head node of given linked list */
void rearrange(struct node *odd)
{
// If linked list has less than 3 nodes, no change is required
if (odd == NULL || odd->next == NULL || odd->next->next == NULL)
return;
return 0;
}
Output:
Time Complexity: The above code simply traverses the given linked list. So time complexity
is O(n)
Auxiliary Space: O(1)
This article is contributed by Aman Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
http://www.geeksforgeeks.org/given-linked-list-reverse-alternate-nodes-append-end/
Category: Linked Lists
Construct a Maximum Sum Linked List out of two Sorted Linked Lists
having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from
start to end. The result list may contain nodes from both input lists. When constructing the
result list, we may switch to the other input list only at the point of intersection (which
mean the two node with the same value in the lists). You are allowed to use O(1) extra
space.
Input:
List1 = 1->3->30->90->120->240->511
List2 = 0->3->12->32->90->125->240->249
Output: Following is maximum sum linked list out of two input lists
list = 1->3->12->32->90->125->240->511
we switch at 3 and 240 to get above maximum sum linked list
We strongly recommend to minimize the browser and try this yourself first.
The idea here in the below solution is to adjust next pointers after common nodes.
1. Start with head of both linked lists and find first common node. Use merging technique
of sorted linked list for that.
2. Keep track of sum of the elements too while doing this and set head of result list based
on greater sum till first common node.
3. After this till the current pointers of both lists don’t become NULL we need to adjust the
next of prev pointers based on greater sum.
This way it can be done in-place with constant extra space.
Time complexity of the below solution is O(n).
// 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;
finalMaxSumList(head1, head2);
return 0;
}
Output:
Source
http://www.geeksforgeeks.org/maximum-sum-linked-list-two-sorted-linked-lists-
common-nodes/
Category: Linked Lists
Input: (0,10)->(1,10)->(5,10)->(7,10)
|
(7,5)->(20,5)->(40,5)
Output: Linked List should be changed to following
(0,10)->(7,10)
|
(7,5)->(40,5)
The given linked list represents a horizontal line from (0,10)
to (7, 10) followed by a vertical line from (7, 10) to (7, 5),
followed by a horizontal line from (7, 5) to (40, 5).
Input: (2,3)->(4,3)->(6,3)->(10,3)->(12,3)
Output: Linked List should be changed to following
(2,3)->(12,3)
There is only one vertical line, so all middle points are removed.
// Utility function to remove Next from linked list and link nodes
// after it to head
void deleteNode(struct node *head, struct node *Next)
{
head->next = Next->next;
Next->next = NULL;
free(Next);
}
return head;
}
push(&head, 40,5);
push(&head, 20,5);
push(&head, 10,5);
push(&head, 10,8);
push(&head, 10,10);
push(&head, 3,10);
push(&head, 1,10);
push(&head, 0,10);
printf("Given Linked List: \n");
printList(head);
if (deleteMiddle(head) != NULL);
{
printf("Modified Linked List: \n");
printList(head);
}
return 0;
}
Output:
Given Linked List:
(0,10)-> (1,10)-> (3,10)-> (10,10)-> (10,8)-> (10,5)-> (20,5)-> (40,5)->
Modified Linked List:
(0,10)-> (10,10)-> (10,5)-> (40,5)->
Time Complexity of the above solution is O(n) where n is number of nodes in given linked
list.
Exercise:
The above code is recursive, write an iterative code for the same problem.
This article is contributed by Sanket Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
http://www.geeksforgeeks.org/given-linked-list-line-segments-remove-middle-points/
Category: Linked Lists
Post navigation
← Given n appointments, find all conflicting appointments Bharti SoftBank (Portal Team)
Interview Experience (Off-Campus) →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
//Node constructor
public Node(int data)
{
this.data = data;
this.next = this.random = null;
}
}
// Driver Class
class Main
{
// Main method.
public static void main(String[] args)
{
// Pushing data in the linked list.
LinkedList list = new LinkedList(new Node(5));
list.push(4);
list.push(3);
list.push(2);
list.push(1);
Output:
new_node->data = malloc(data_size);
new_node->next = (*head_ref);
Output:
Created integer linked list is
10 20 30 40 50
This article is contributed by Himanshu Gupta. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
http://www.geeksforgeeks.org/generic-linked-list-in-c-2/
Category: C/C++ Puzzles Linked Lists
This may look a simple problem, but is interesting question as it has following cases to be
handled.
1) x and y may or may not be adjacent.
2) Either x or y may be a head node.
3) Either x or y may be last node.
4) x and/or y may not be present in linked list.
How to write a clean working code that handles all of the above possibilities.
We strongly recommend to minimize your browser and try this yourself first.
The idea it to first search x and y in given linked list. If any of them is not present, then
return. While searching for x and y, keep track of current and previous pointers. First
change next of previous pointers, then change next of current pointers. Following is C
implementation of this approach.
#include<stdio.h>
#include<stdlib.h>
swapNodes(&start, 4, 3);
return 0;
}
Output:
Optimizations: The above code can be optimized to search x and y in single traversal. Two
loops are used to keep program simple.
This article is contributed by Gautam. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
http://www.geeksforgeeks.org/swap-nodes-in-a-linked-list-without-swapping-data/
Category: Linked Lists
Point to next higher value node in a linked list with an arbitrary
pointer
Given singly linked list with every node having an additional “arbitrary” pointer that
currently points to NULL. Need to make the “arbitrary” pointer point to the next higher
value node.
We strongly recommend to minimize your browser and try this yourself first
A Simple Solution is to traverse all nodes one by one, for every node, find the node which
has next greater value of current node and change the next pointer. Time Complexity of this
solution is O(n2.
An Efficient Solution works in O(nLogn) time. The idea is to use Merge Sort for linked list.
1) Traverse input list and copy next pointer to arbit pointer for every node.
2) Do Merge Sort for the linked list formed by arbit pointers.
Below is C implementation of above idea. All of the merger sort functions are taken from
here. The taken functions are modified here so that they work on arbit pointers instead of
next pointers.
/* Base cases */
if (a == NULL)
return (b);
else if (b==NULL)
return (a);
return (result);
}
/* Split the nodes of the given list into front and back halves,
and return the two lists using the reference parameters.
If the length is odd, the extra node should go in the front list.
Uses the fast/slow pointer strategy. */
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef)
{
struct node* fast, *slow;
if (source==NULL || source->arbit==NULL)
{
/* length < 2 cases */
*frontRef = source;
*backRef = NULL;
return;
}
new_node->arbit = NULL;
getchar();
return 0;
}
Output:
This article is contributed by Saurabh Bansal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
http://www.geeksforgeeks.org/point-to-next-higher-value-node-in-a-linked-list-with-an-
arbitrary-pointer/
Category: Linked Lists
Post navigation
← Pythagorean Triplet in an array Flipkart Interview Experience | Set 22 (For SDE 2) →
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the
link here.
We strongly recommend to minimize your browser and try this yourself first.
Merge sort for singly linked list is already discussed. The important change here is to
modify the previous pointers also when merging two lists.
Below is C implementation of merge sort for doubly linked list.
// Driver program
int main(void)
{
struct node *head = NULL;
insert(&head,5);
insert(&head,20);
insert(&head,4);
insert(&head,3);
insert(&head,30);
insert(&head,10);
printf("Linked List before sorting\n");
print(head);
head = mergeSort(head);
printf("\n\nLinked List after sorting\n");
print(head);
return 0;
}
Output:
Linked List before sorting
Forward Traversal using next pointer
10 30 3 4 20 5
Backward Traversal using prev pointer
5 20 4 3 30 10
Source
http://www.geeksforgeeks.org/merge-sort-for-doubly-linked-list/
Category: Linked Lists
Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
Why is Quick Sortpreferred for arrays?
Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays.
Recursive Quick Sort for array.
Iterative Quick Sort for arrays.
Recursive Merge Sort for arrays
Iterative Merge Sort for arrays
Quick Sort in its general form is an in-place sort (i.e. it doesn’t require any extra storage)
whereas merge sort requires O(N) extra storage, N denoting the array size which may be
quite expensive. Allocating and de-allocating the extra space used for merge sort increases
the running time of the algorithm. Comparing average complexity we find that both type of
sorts have O(NlogN) average complexity but the constants differ. For arrays, merge sort
loses due to the use of extra O(N) storage space.
Most practical implementations of Quick Sort use randomized version. The randomized
version has expected time complexity of O(nLogn). The worst case is possible in
randomized version also, but worst case doesn’t occur for a particular pattern (like sorted
array) and randomized Quick Sort works well in practice.
Quick Sort is also a cache friendly sorting algorithm as it has good locality of reference
when used for arrays.
Quick Sort is also tail recursive, therefore tail call optimizations is done.
Why is Merge Sortpreferred for Linked Lists?
Below are implementations of Quicksort and Mergesort for singly and doubly linked lists.
Quick Sort for Doubly Linked List
Quick Sort for Singly Linked List
Merge Sort for Singly Linked List
Merge Sort for Doubly Linked List
In case of linked lists the case is different mainly due to difference in memory allocation of
arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory.
Unlike array, in linked list, we can insert items in the middle in O(1) extra space and O(1)
time. Therefore merge operation of merge sort can be implemented without extra space for
linked lists.
In arrays, we can do random access as elements are continuous in memory. Let us say we
have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can
directly access the memory at (x + i*4). Unlike arrays, we can not do random access in
linked list. Quick Sort requires a lot of this kind of access. In linked list to access i’th index,
we have to travel each and every node from the head to i’th node as we don’t have
continuous block of memory. Therefore, the overhead increases for quick sort. Merge sort
accesses data sequentially and the need of random access is low.
Thanks to Sayan Mukhopadhyay for providing initial draft for above article. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
Source
http://www.geeksforgeeks.org/why-quick-sort-preferred-for-arrays-and-merge-sort-for-
linked-lists/
return new_node;
}
printRandom(head);
return 0;
}
Similarly we can show probability for 3rd last node and other nodes.
This article is contributed by Rajeev. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
http://www.geeksforgeeks.org/select-a-random-node-from-a-singly-linked-list/
Source: http://qa.geeksforgeeks.org/616/linked-that-sorted-alternating-ascending-
descending-orders
We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to use Merge Sort for linked List. This solution takes O(n Log n) time.
An Efficient Solution works in O(n) time. Below are all steps.
1. Separate two lists.
2. Reverse the one with descending order
3. Merge both lists. Below is C++ implementation based on above idea.
Below is C++ implementation of above algorithm.
ascn->next = NULL;
dscn->next = NULL;
*Ahead = (*Ahead)->next;
*Dhead = (*Dhead)->next;
}
return 0;
}
Output:
Given Linked List is
10 40 53 30 67 12 89
Source
http://www.geeksforgeeks.org/how-to-sort-a-linked-list-that-is-sorted-alternating-
ascending-and-descending-orders/
Category: Linked Lists
Examples:
Input: 1 -> 2 -> 3 -> 4
Output: 1 -> 4 -> 2 -> 3
We strongly recommend you to minimize your browser and try this yourself first.
Simple Solution
1) Initialize current node as head.
2) While next of current node is not null, do following
a) Find the last node, remove it from end and insert it as next
of current node.
b) Move current to next to next of current
Time complexity of the above simple solution is O(n2) where n is number of nodes in linked
list.
Efficient Solution:
while (curr)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
*head = prev;
}
// Driver program
int main()
{
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);
Output: