The Wayback Machine - https://web.archive.org/web/20240927074230/https://www.geeksforgeeks.org/modify-contents-linked-list/
Open In App

Modify contents of Linked List

Last Updated : 10 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
72.39%
21.6K

Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle node remains unchanged. 
(No extra memory to be used).

Examples:  

Input : 10 -> 4 -> 5 -> 3 -> 6
Output : 4 -> 1 -> 5 -> 3 -> 6

Input : 2 -> 9 -> 8 -> 12 -> 7 -> 10
Output : -8 -> 2 -> -4 -> 12 -> 7 -> 10

Asked in Amazon Interview

Recommended Problem

Approach: The following steps are:

  1. Split the list from the middle. Perform front and back split. If the number of elements is odd, the extra element should go in the 1st(front) list.
  2. Reverse the 2nd(back) list.
  3. Perform the required subtraction while traversing both list simultaneously.
  4. Again reverse the 2nd list.
  5. Concatenate the 2nd list back to the end of the 1st list.

Implementation:

C++




// 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);
          
    // again 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;
} 


Java




// Java implementation to modify the contents 
// of the linked list
class GFG
{
      
/* Linked list node */
static class Node
{
    int data;
    Node next;
};
  
/* Function to insert a node at the beginning 
of the linked list */
static Node 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 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;
      
    return head_ref;
} 
  
static Node front,back;
  
/* 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. */
static void frontAndBackSplit( Node head)
{
    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 = head;
    back = slow.next;
    slow.next = null;
}
  
/* Function to reverse the linked list */
static Node reverseList( Node head_ref)
{
    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;
    return head_ref;
}
  
// perform the required subtraction operation 
// on the 1st half of the linked list
static void modifyTheContentsOf1stHalf()
{
    Node front1 = front, back1 = back;
    // traversing both the lists simultaneously
    while (back1 != null)
    {
        // subtraction operation and node data
        // modification
        front1.data = front1.data - back1.data;
          
        front1 = front1.next;
        back1 = back1.next;
    }
}
  
// function to concatenate the 2nd(back) list 
// at the end of the 1st(front) list and 
// returns the head of the new list
static Node concatFrontAndBackList(Node front,
                                   Node back)
{
    Node head = front;
      
    if(front == null)return back;
      
    while (front.next != null)
        front = front.next; 
          
    front.next = back;
      
    return head;
}
  
// function to modify the contents of the linked list
static Node modifyTheList( Node head)
{
    // if list is empty or contains only single node
    if (head == null || head.next == null)
        return head;
    front = null; back = null;
      
    // split the list into two halves
    // front and back lists
    frontAndBackSplit(head);
          
    // reverse the 2nd(back) list
    back = reverseList(back);
      
    // modify the contents of 1st half 
    modifyTheContentsOf1stHalf();
      
    // agains reverse the 2nd(back) list
    back = 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
static void printList( Node head)
{
    if (head == null)
        return;
      
    while (head.next != null)
    {
        System.out.print(head.data + " -> ");
        head = head.next;
    }
    System.out.println(head.data );
}
  
// Driver Code
public static void main(String args[])
{
    Node head = null;
      
    // creating the linked list
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 12);
    head = push(head, 8);
    head = push(head, 9);
    head = push(head, 2);
      
    // modify the linked list
    head = modifyTheList(head);
      
    // print the modified linked list
    System.out.println( "Modified List:" );
    printList(head);
}
}
  
// This code is contributed by Arnab Kundu


Python3




# Python3 implementation to modify the contents 
# of the linked list
  
# Linked list node 
class Node: 
      
    def __init__(self, data): 
        self.data = data 
        self.next = None
  
# Function to insert a node at the beginning 
# of the linked list 
def push(head_ref, new_data):
  
    # allocate node 
    new_node =Node(0)
      
    # 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
      
    return head_ref
  
front = None
back = None
  
# 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. 
def frontAndBackSplit( head):
  
    global front
    global back
    slow = None
    fast = None
      
    slow = head
    fast = head.next
      
    # Advance 'fast' two nodes, and 
    # advance 'slow' one node 
    while (fast != None):
      
        fast = fast.next
        if (fast != None):
            slow = slow.next
            fast = fast.next
  
    # 'slow' is before the midpoint in the list, 
    # so split it in two at that point. 
    front = head
    back = slow.next
    slow.next = None
    return head
  
# Function to reverse the linked list 
def reverseList( head_ref):
  
    current = None
    prev = None
    next = None
    current = head_ref
    prev = None
    while (current != None):
      
        next = current.next
        current.next = prev
        prev = current
        current = next
      
    head_ref = prev
    return head_ref
  
# perform the required subtraction operation 
# on the 1st half of the linked list
def modifyTheContentsOf1stHalf():
  
    global front
    global back
    front1 = front
    back1 = back
      
    # traversing both the lists simultaneously
    while (back1 != None):
      
        # subtraction operation and node data
        # modification
        front1.data = front1.data - back1.data
          
        front1 = front1.next
        back1 = back1.next
      
# function to concatenate the 2nd(back) list 
# at the end of the 1st(front) list and 
# returns the head of the new list
def concatFrontAndBackList( front, back):
      
    head = front
      
    if(front == None):
        return back
      
    while (front.next != None):
        front = front.next
          
    front.next = back
    return head
  
# function to modify the contents of the linked list
def modifyTheList( head):
  
    global front
    global back
  
    # if list is empty or contains only single node
    if (head == None or head.next == None):
        return head
    front = None
    back = None
      
    # split the list into two halves
    # front and back lists
    frontAndBackSplit(head)
          
    # reverse the 2nd(back) list
    back = reverseList(back)
      
    # modify the contents of 1st half 
    modifyTheContentsOf1stHalf()
      
    # agains reverse the 2nd(back) list
    back = 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
def printList( head):
  
    if (head == None):
        return
      
    while (head.next != None):
      
        print(head.data , " -> ",end="")
        head = head.next
      
    print(head.data )
  
# Driver Code
  
head = None
      
# creating the linked list
head = push(head, 10)
head = push(head, 7)
head = push(head, 12)
head = push(head, 8)
head = push(head, 9)
head = push(head, 2)
      
# modify the linked list
head = modifyTheList(head)
      
# print the modified linked list
print( "Modified List:" )
printList(head)
  
# This code is contributed by Arnab Kundu


C#




// C# implementation to modify the 
// contents of the linked list
using System;
  
class GFG
{
      
/* Linked list node */
public class Node
{
    public int data;
    public Node next;
};
  
/* Function to insert a node at 
the beginning of the linked list */
static Node 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 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;
      
    return head_ref;
} 
  
static Node front, back;
  
/* 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. */
static void frontAndBackSplit( Node head)
{
    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 = head;
    back = slow.next;
    slow.next = null;
}
  
/* Function to reverse the linked list */
static Node reverseList(Node head_ref)
{
    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;
    return head_ref;
}
  
// perform the required subtraction operation 
// on the 1st half of the linked list
static void modifyTheContentsOf1stHalf()
{
    Node front1 = front, back1 = back;
      
    // traversing both the lists simultaneously
    while (back1 != null)
    {
        // subtraction operation and node data
        // modification
        front1.data = front1.data - back1.data;
          
        front1 = front1.next;
        back1 = back1.next;
    }
}
  
// function to concatenate the 2nd(back) list 
// at the end of the 1st(front) list and 
// returns the head of the new list
static Node concatFrontAndBackList(Node front,
                                   Node back)
{
    Node head = front;
      
    if(front == null)
        return back;
      
    while (front.next != null)
        front = front.next; 
          
    front.next = back;
      
    return head;
}
  
// function to modify the contents of
// the linked list
static Node modifyTheList(Node head)
{
    // if list is empty or contains 
    // only single node
    if (head == null || head.next == null)
        return head;
    front = null; back = null;
      
    // split the list into two halves
    // front and back lists
    frontAndBackSplit(head);
          
    // reverse the 2nd(back) list
    back = reverseList(back);
      
    // modify the contents of 1st half 
    modifyTheContentsOf1stHalf();
      
    // agains reverse the 2nd(back) list
    back = 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
static void printList( Node head)
{
    if (head == null)
        return;
      
    while (head.next != null)
    {
        Console.Write(head.data + " -> ");
        head = head.next;
    }
    Console.WriteLine(head.data );
}
  
// Driver Code
public static void Main()
{
    Node head = null;
      
    // creating the linked list
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 12);
    head = push(head, 8);
    head = push(head, 9);
    head = push(head, 2);
      
    // modify the linked list
    head = modifyTheList(head);
      
    // print the modified linked list
    Console.WriteLine( "Modified List:" );
    printList(head);
}
}
  
// This code is contributed by PrinciRaj1992


Javascript




<script>
  
      // JavaScript implementation to modify the
      // contents of the linked list
      /* Linked list node */
      class Node {
        constructor() {
          this.data = 0;
          this.next = null;
        }
      }
  
      /* Function to insert a node at
       the beginning of the linked list */
       function push(head_ref, new_data) {
        /* allocate node */
        var new_node = new 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;
  
        return head_ref;
      }
  
      var front, back;
  
      /* 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. */
      function frontAndBackSplit(head) {
        var 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 = head;
        back = slow.next;
        slow.next = null;
      }
  
      /* Function to reverse the linked list */
      function reverseList(head_ref) {
        var current, prev, next;
        current = head_ref;
        prev = null;
        while (current != null) {
          next = current.next;
          current.next = prev;
          prev = current;
          current = next;
        }
        head_ref = prev;
        return head_ref;
      }
  
      // perform the required subtraction operation
      // on the 1st half of the linked list
      function modifyTheContentsOf1stHalf() {
        var front1 = front,
          back1 = back;
  
        // traversing both the lists simultaneously
        while (back1 != null) {
          // subtraction operation and node data
          // modification
          front1.data = front1.data - back1.data;
  
          front1 = front1.next;
          back1 = back1.next;
        }
      }
  
      // function to concatenate the 2nd(back) list
      // at the end of the 1st(front) list and
      // returns the head of the new list
      function concatFrontAndBackList(front, back) {
        var head = front;
  
        if (front == null) return back;
  
        while (front.next != null) front = front.next;
  
        front.next = back;
  
        return head;
      }
  
      // function to modify the contents of
      // the linked list
      function modifyTheList(head) {
        // if list is empty or contains
        // only single node
        if (head == null || head.next == null) return head;
        front = null;
        back = null;
  
        // split the list into two halves
        // front and back lists
        frontAndBackSplit(head);
  
        // reverse the 2nd(back) list
        back = reverseList(back);
  
        // modify the contents of 1st half
        modifyTheContentsOf1stHalf();
  
        // agains reverse the 2nd(back) list
        back = 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
      function printList(head) {
        if (head == null) return;
  
        while (head.next != null) {
          document.write(head.data + " -> ");
          head = head.next;
        }
        document.write(head.data + "<br>");
      }
  
      // Driver Code
      var head = null;
  
      // creating the linked list
      head = push(head, 10);
      head = push(head, 7);
      head = push(head, 12);
      head = push(head, 8);
      head = push(head, 9);
      head = push(head, 2);
  
      // modify the linked list
      head = modifyTheList(head);
  
      // print the modified linked list
      document.write("Modified List: <br>");
      printList(head);
        
</script>


Output

Modified List:
-8 -> 2 -> -4 -> 12 -> 7 -> 10

Time Complexity: O(n), where n in the number of nodes.
Space complexity: O(1) since using constant space to modify pointers

Another approach (Using Stack) : 

  1. Find the starting point of second half Linked List. 
  2. Push all elements of second half list into stack s. 
  3. Traverse list starting from head using temp until stack is not empty and do Modify temp->data by subtracting the top element of stack for every node.

Below is the implementation using stack. 

C++




// 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


Java




// Java implementation to modify the
// contents of the linked list
import java.util.*;
  
class GFG 
{
  
    // Linked list node
    static class Node 
    {
  
        int data;
        Node next;
    };
  
    // Function to insert a node at the
    // beginning of the linked list
    static Node 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 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;
        return head_ref;
    }
  
    // function to print the linked list
    static void printList(Node head) 
    {
        if (head == null) 
        {
            return;
        }
  
        while (head.next != null) 
        {
            System.out.print(head.data + "->");
            head = head.next;
        }
        System.out.print(head.data + "\n");
    }
  
    // Function to middle node of list.
    static Node find_mid(Node head) 
    {
        Node temp = head, slow = head, fast = head;
  
        while (fast != null && fast.next != null)
        {
  
            // 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 != null) 
        {
            slow = slow.next;
        }
  
        return slow;
    }
  
    // function to modify the contents of the linked list.
    static void modifyTheList(Node head, Node slow) 
    {
        // Create Stack. 
        Stack<Integer> s = new Stack<Integer>();
        Node temp = head;
  
        while (slow != null) 
        {
            s.add(slow.data);
            slow = slow.next;
        }
  
    // Traverse the list by using temp until stack is empty.
        while (!s.empty())
        {
            temp.data = temp.data - s.peek();
            temp = temp.next;
            s.pop();
        }
  
    }
  
    // Driver program to test above
    public static void main(String[] args)
    {
        Node head = null, mid;
  
        // creating the linked list
        head = push(head, 10);
        head = push(head, 7);
        head = push(head, 12);
        head = push(head, 8);
        head = push(head, 9);
        head = 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
        System.out.print("Modified List:" + "\n");
        printList(head);
    }
}
  
// This code is contributed by Rajput-Ji


Python3




# Python3 implementation to modify the
# contents of the linked list
   
# Linked list node
class Node:
      
    def __init__(self):
          
        self.data = 0
        self.next = None
   
# Function to insert a node at the
# beginning of the linked list
def append(head_ref, new_data):
  
    # Allocate node
    new_node = 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
      
    return head_ref
      
# Function to print the linked list
def printList(head):
  
    if (not head):
        return;
       
    while (head.next != None):
        print(head.data, end = ' -> ')
        head = head.next
      
    print(head.data)
      
# Function to middle node of list.
def find_mid(head):
  
    temp = head
    slow = head
    fast = head 
       
    while (fast and 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.
def modifyTheList(head, slow):
  
    # Create Stack. 
    s = []
    temp = head 
      
    while (slow):
        s.append(slow.data) 
        slow = slow.next 
  
    # Traverse the list by using 
    # temp until stack is empty.
    while (len(s) != 0):
        temp.data = temp.data - s[-1]
        temp = temp.next 
        s.pop() 
      
# Driver code
if __name__=='__main__':
      
    head = None
       
    # creating the linked list
    head = append(head, 10)
    head = append(head, 7)
    head = append(head, 12)
    head = append(head, 8)
    head = append(head, 9)
    head = append(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
    print("Modified List:")
    printList(head)
  
# This code is contributed by rutvik_56


C#




// C# implementation to modify the
// contents of the linked list
using System;
using System.Collections.Generic;
  
class GFG 
{
  
    // Linked list node
    public class Node 
    {
  
        public int data;
        public Node next;
    };
  
    // Function to insert a node at the
    // beginning of the linked list
    static Node 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 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;
        return head_ref;
    }
  
    // function to print the linked list
    static void printList(Node head) 
    {
        if (head == null) 
        {
            return;
        }
  
        while (head.next != null) 
        {
            Console.Write(head.data + "->");
            head = head.next;
        }
        Console.Write(head.data + "\n");
    }
  
    // Function to middle node of list.
    static Node find_mid(Node head) 
    {
        Node temp = head, slow = head, fast = head;
  
        while (fast != null && fast.next != null)
        {
  
            // 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 != null) 
        {
            slow = slow.next;
        }
  
        return slow;
    }
  
    // function to modify the contents of the linked list.
    static void modifyTheList(Node head, Node slow) 
    {
        // Create Stack. 
        Stack<int> s = new Stack<int>();
        Node temp = head;
  
        while (slow != null) 
        {
            s.Push(slow.data);
            slow = slow.next;
        }
  
        // Traverse the list by using temp until stack is empty.
        while (s.Count != 0)
        {
            temp.data = temp.data - s.Peek();
            temp = temp.next;
            s.Pop();
        }
  
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        Node head = null, mid;
  
        // creating the linked list
        head = push(head, 10);
        head = push(head, 7);
        head = push(head, 12);
        head = push(head, 8);
        head = push(head, 9);
        head = 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
        Console.Write("Modified List:" + "\n");
        printList(head);
    }
}
  
// This code is contributed by PrinciRaj1992


Javascript




<script>
  
// JavaScript implementation to modify the
// contents of the linked list
  
    // Linked list node
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
  
    // Function to insert a node at the
    // beginning of the linked list
    function push(head_ref , new_data) {
  
        // allocate node
        var new_node = new 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;
        return head_ref;
    }
  
    // function to print the linked list
    function printList(head) {
        if (head == null) {
            return;
        }
  
        while (head.next != null) {
            document.write(head.data + "->");
            head = head.next;
        }
        document.write(head.data + "<br/>");
    }
  
    // Function to middle node of list.
    function find_mid(head) {
    var temp = head, slow = head, fast = head;
  
        while (fast != null && fast.next != null) {
  
            // 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 != null) {
            slow = slow.next;
        }
  
        return slow;
    }
  
    // function to modify the contents of the linked list.
    function modifyTheList(head,  slow) {
        // Create Stack.
        var s = [];
        var temp = head;
  
        while (slow != null) {
            s.push(slow.data);
            slow = slow.next;
        }
  
        // Traverse the list by using temp until stack is empty.
        while (s.length!=0) {
            temp.data = temp.data - s.pop();
            temp = temp.next;
              
        }
  
    }
  
    // Driver program to test above
      
        var head = null, mid;
  
        // creating the linked list
        head = push(head, 10);
        head = push(head, 7);
        head = push(head, 12);
        head = push(head, 8);
        head = push(head, 9);
        head = 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
        document.write("Modified List:" + "<br/>");
        printList(head);
  
// This code contributed by Rajput-Ji
  
</script>


Output

Modified List:
-8 -> 2 -> -4 -> 12 -> 7 -> 10

Time Complexity : O(n) 
Space Complexity : O(n/2)



Similar Reads

Modify contents of Linked List - Recursive approach
Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle n
11 min read
How to write C functions that modify head pointer of a Linked List?
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other ope
4 min read
Modify Linked List by replacing each node by nearest multiple of K
Given a singly Linked List L consisting of N nodes and an integer K, the task is to modify the value of each node of the given Linked List to its nearest multiple of K, not exceeding the value of the node. Examples: Input: LL: 1 -> 2 -> 3 -> 5, K = 2 Output: 0 -> 2 -> 2 -> 4Explanation:The resultant LL has values having less than
7 min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Modify a Linked List to contain last occurrences of every duplicate element
Given an unsorted Singly Linked List consisting of N nodes that may contain duplicate elements, the task is to remove all but the last occurrence of duplicate elements from the Linked List. Examples: Input: 1 -> 2 -> 7 -> 3 -> 2 -> 5 -> 1Output: 7 -> 3 -> 2 -> 5 -> 1Explanation: Given Linked List: 1 -> 2 -> 7 -
10 min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1->2->3->2->4->5->2->4, Head2 = 2->4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3->4->1->5->2, Head2 = 3->4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1, K = 3Output: 7<–>6<–>8<–>1<–>3<–>11 Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1 <–
14 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5->2->3->8list2 = 1->7->4->5Output: New list = 5->7->4->8Input: list1 = 2->8->9->3li
8 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2->4->6->7->5 Output: trueExplanation: As shown in figure the first a
12 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Insert a linked list into another linked list
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place. Examples: Input: a = 3, b = 4head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15, head2: 100 -> 101 -> 102 -> 103Output: 10 -> 11 -> 12 -> 100 -> 101 -
10 min read
Convert singly linked list into circular linked list
Given a singly linked list, the task is to convert it into a circular linked list. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head. Input: head: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> NULLOutput: Explanation: Singly l
11 min read
Merge a linked list into another linked list at alternate positions
Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer. Example: Input: head1: 1->2->3 , head2: 4->5->6->7->8Output: head1: 1->4->2->5->3->6 , head2: 7->8 Input: hea
8 min read
Modify and Rearrange List
Given a singly linked list, with some positive numbers (valid numbers) and zeros (invalid numbers). Convert the linked list in such a way that if next valid number is same as current number, double its value and replace the next number with 0. After the modification, rearrange the linked list such that all 0’s are shifted to the end. Examples: Inpu
13 min read
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 us
14 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -> 2 -> 3 -> 8 -> NULL list2 = 1 -> 7 -> 4 -> 5 -> NULL Output: 5 -> 7 -> 4
11 min read
Construct a Doubly linked linked list from 2D Matrix
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to construct a new node for every element of the matrix
15+ min read
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples: Input : 10 / \ 8 2 / \ 3 5 Output : 10 \ 8 \ 3 \ 5 \ 2 Explanation : The preorder traversal of given binary tree is 10 8 3 5 2. Method
15 min read
Article Tags :
Practice Tags :