{"id":3757,"date":"2021-08-10T09:27:08","date_gmt":"2021-08-10T09:27:08","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=3757"},"modified":"2023-07-27T12:44:36","modified_gmt":"2023-07-27T12:44:36","slug":"swap-nodes-in-a-linked-list-without-swapping-data","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/","title":{"rendered":"Swap Nodes in a Linked List Without Swapping Data"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png\" alt=\"\" \/><\/p>\n<p>A linked list is a type of data structure that stores a sequence of elements, each of which points to the next element in the sequence. Linked lists are made up of nodes, each of which contains data as well as a pointer to the next node in the sequence. The first node is referred to as the head node, and the last node is referred to as the tail node. Because they can be dynamically resized, linked lists are commonly used in programming to implement other data structures such as stacks, queues, and hash tables. In this section, we will be discussing how we swap two nodes in linked list<\/p>\n<p>.<\/p>\n<h2>How to Swap Two Nodes in Linked List Without Swapping Data? <\/h2>\n<p>In this problem, we will be discussing how we can swap nodes directly by changing links rather than swapping out the data. We will be given a <a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/a-brief-introduction-to-linked-lists\/\">linked list<\/a> and two keys say x and y, and we have to swap the nodes of the linked list having these keys as data.<\/p>\n<p><strong>Note:<\/strong> All the keys in the linked list are unique, i.e. no two nodes in the linked list will have the same data.<\/p>\n<h3>Understanding How swapping nodes in a linked list Works<\/h3>\n<p>Let\u2019s try to understand what the actual problem is, so basically here, we will be given a linked list and two keys x and y. We will have to iterate the linked list and search for the nodes with keys x and y. Once we got the nodes with the keys x and y, we will have to swap these nodes. We can swap nodes of linked list either by swapping their data or by changing the links (swapping nodes). Here we will be swapping the nodes by changing the links of the nodes.<\/p>\n<p><strong>Input:<\/strong> <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/51_INPUT-01.png\" alt=\"\" \/><\/p>\n<p>Keys are 2 and 4 (x=2 and y=4).<\/p>\n<p><strong>Output (After swapping the nodes):<\/strong> <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/51-01.png\" alt=\"\" \/><\/p>\n<p>Which method of swapping is more efficient, swapping by data or swapping by nodes?<\/p>\n<p>In LinkedList, if we have to swap the data of two nodes, it\u2019s easy if there are fewer fields, and it would also take less time but if the data inside the nodes is large then swapping that amount of data can limit the speed of the process. For this reason, swapping nodes is preferred. <\/p>\n<p>Now let\u2019s move to the approach section, there we will see how we will solve the above problem of searching the nodes and swapping.<\/p>\n<h2>Approach to swap two nodes in linked list without swapping data<\/h2>\n<p>Swapping nodes seem easy if the nodes to be swapped are adjacent, but then it becomes difficult for the following cases: <\/p>\n<ul>\n<li>The first case is when x and y are not adjacent.<\/li>\n<li>Or may be either of x and y is head nodes.<\/li>\n<li>Or maybe either x or y is the last node.<\/li>\n<li>And there can be a case where x and\/or y may not even be present in the linked list.<\/li>\n<\/ul>\n<p>The idea is to search for the two nodes with keys x and y, if any of them is not present then return null otherwise change the next pointers of the two nodes.<\/p>\n<h2>Algorithm to swap the nodes in a linked list without swapping data<\/h2>\n<ul>\n<li>Search for x and y nodes in the LinkedList.<\/li>\n<li>If any of them is NULL, return.<\/li>\n<li>Take 4 pointers as <strong>previousX<\/strong>, <strong>currentX<\/strong>, <strong>previousY<\/strong>, <strong>currentY<\/strong> to denote the previous and current nodes of x and y respectively.<\/li>\n<li>If x is not head of the linked list, then change previousX-&gt;next = currentY and if x is head of the linked list then make node y as the new head of the linked list.<\/li>\n<li>If y is not head of the linked list, then change previousY-&gt;next = currentX and if y is the head of the linked list then make node x as the new head of the linked list.<\/li>\n<li>Finally, swap the next pointers of the current nodes as currentX-&gt;next to currentY-&gt;next.<\/li>\n<\/ul>\n<h3>Dry Run <\/h3>\n<p>Let me dry run this for a small test case, then it will be much clearer to understand. In the following example, we have a linked list, and we need to swap the two nodes having keys as 2 and 4.<br \/>\n<img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/51_1-01.png\" alt=\"\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/51_2-01.png\" alt=\"\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/51_3-01.png\" alt=\"\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/51_4-01.png\" alt=\"\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/51_5-01.png\" alt=\"\" \/><\/p>\n<h3>Code Implementation<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_3758 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_3758 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_3758 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_3758 .wpsm_nav-tabs > li.active > a, #tab_container_3758 .wpsm_nav-tabs > li.active > a:hover, #tab_container_3758 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_3758 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_3758 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_3758 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_3758 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_3758 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_3758 .wpsm_nav-tabs > li > a:hover , #tab_container_3758 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_3758 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_3758 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_3758 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_3758 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_3758 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_3758 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_3758 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_3758 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_3758 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_3758 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_3758 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_3758\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_3758\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3758_1\" aria-controls=\"tabs_desc_3758_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3758_2\" aria-controls=\"tabs_desc_3758_2\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C++<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3758_3\" aria-controls=\"tabs_desc_3758_3\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3758_4\" aria-controls=\"tabs_desc_3758_4\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_3758\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_3758_1\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"c\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"c\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n \r\n\/* A linked list node *\/\r\nstruct Node {\r\n    int data;\r\n    struct Node* next;\r\n};\r\n \r\nvoid swapNodes(struct Node** head_ref, int x, int y)\r\n{\r\n    if (x == y)\r\n        return;\r\n \r\n    struct Node *prevX = NULL, *currX = *head_ref;\r\n    while (currX &amp;&amp; currX-&gt;data != x) {\r\n        prevX = currX;\r\n        currX = currX-&gt;next;\r\n    }\r\n \r\n    struct Node *prevY = NULL, *currY = *head_ref;\r\n    while (currY &amp;&amp; currY-&gt;data != y) {\r\n        prevY = currY;\r\n        currY = currY-&gt;next;\r\n    }\r\n \r\n    if (currX == NULL || currY == NULL)\r\n        return;\r\n \r\n    if (prevX != NULL)\r\n        prevX-&gt;next = currY;\r\n    else \/\/ Else make y as new head\r\n        *head_ref = currY;\r\n \r\n    \/\/ If y is not head of linked list\r\n    if (prevY != NULL)\r\n        prevY-&gt;next = currX;\r\n    else \/\/ Else make x as new head\r\n        *head_ref = currX;\r\n \r\n    \/\/ Swap next pointers\r\n    struct Node* temp = currY-&gt;next;\r\n    currY-&gt;next = currX-&gt;next;\r\n    currX-&gt;next = temp;\r\n}\r\n \r\n\/* Function to add a node at the beginning of List *\/\r\nvoid push(struct Node** head_ref, int new_data)\r\n{\r\n    \/* allocate node *\/\r\n    struct Node* new_node\r\n        = (struct Node*)malloc(sizeof(struct Node));\r\n \r\n    \/* put in the data  *\/\r\n    new_node-&gt;data = new_data;\r\n \r\n    \/* link the old list off the new node *\/\r\n    new_node-&gt;next = (*head_ref);\r\n \r\n    \/* move the head to point to the new node *\/\r\n    (*head_ref) = new_node;\r\n}\r\n \r\n\/* Function to print nodes in a given linked list *\/\r\nvoid printList(struct Node* node)\r\n{\r\n    while (node != NULL) {\r\n        printf(&quot;%d &quot;, node-&gt;data);\r\n        node = node-&gt;next;\r\n    }\r\n}\r\n \r\n\/* Driver program to test above function *\/\r\nint main()\r\n{\r\n    struct Node* start = NULL;\r\n \r\n    \/* The constructed linked list is:\r\n     1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7 *\/\r\n    push(&amp;start, 7);\r\n    push(&amp;start, 6);\r\n    push(&amp;start, 5);\r\n    push(&amp;start, 4);\r\n    push(&amp;start, 3);\r\n    push(&amp;start, 2);\r\n    push(&amp;start, 1);\r\n \r\n    printf(&quot;&#92;n Linked list before calling swapNodes() &quot;);\r\n    printList(start);\r\n \r\n    swapNodes(&amp;start, 4, 3);\r\n \r\n    printf(&quot;&#92;n Linked list after calling swapNodes() &quot;);\r\n    printList(start);\r\n \r\n    return 0;\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_3758_2\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"cpp\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include &lt;bits stdc++.h=&quot;&quot;&gt;\r\nusing namespace std;\r\nclass Node {\r\npublic:\r\n    int data;\r\n    Node* next;\r\n};\r\n\r\nvoid swapNodes(Node** head_ref, int x, int y)\r\n{\r\n    if (x == y)\r\n        return;\r\n    Node *previousX = NULL, *currentX = *head_ref;\r\n    while (currentX &amp;&amp; currentX-&gt;data != x) {\r\n        previousX = currentX;\r\n        currentX = currentX-&gt;next;\r\n    }\r\n    Node *previousY = NULL, *currentY = *head_ref;\r\n    while (currentY &amp;&amp; currentY-&gt;data != y) {\r\n        previousY = currentY;\r\n        currentY = currentY-&gt;next;\r\n    }\r\n    if (currentX == NULL || currentY == NULL)\r\n        return;\r\n    if (previousX != NULL)\r\n        previousX-&gt;next = currentY;\r\n    else\r\n        *head_ref = currentY;\r\n\r\n    if (previousY != NULL)\r\n        previousY-&gt;next = currentX;\r\n    else \r\n        *head_ref = currentX;\r\n\r\n    Node* temp = currentY-&gt;next;\r\n    currentY-&gt;next = currentX-&gt;next;\r\n    currentX-&gt;next = temp;\r\n}\r\nvoid push(Node** head_ref, int new_data)\r\n{\r\n    Node* new_node = new Node();\r\n\r\n    \r\n    new_node-&gt;data = new_data;\r\n\r\n    new_node-&gt;next = (*head_ref);\r\n\r\n    (*head_ref) = new_node;\r\n}\r\nvoid printList(Node* node)\r\n{\r\n    while (node != NULL) {\r\n        cout &lt;&lt; node-&gt;data &lt;&lt; &quot; &quot;;\r\n        node = node-&gt;next;\r\n    }\r\n}\r\nint main()\r\n{\r\n    Node* start = NULL;\r\n    push(&amp;start, 5);\r\n    push(&amp;start, 4);\r\n    push(&amp;start, 3);\r\n    push(&amp;start, 2);\r\n    push(&amp;start, 1);\r\n    swapNodes(&amp;start, 2, 4);\r\n    printList(start);\r\n    return 0;\r\n}\r\n\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_3758_3\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"java\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\nclass Node {\r\n    int data;\r\n    Node next;\r\n    Node(int d)\r\n    {\r\n        data = d;\r\n        next = null;\r\n    }\r\n}\r\n\r\nclass LinkedList {\r\n    Node head; \r\n    public void swapNodes(int x, int y)\r\n    {\r\n        if (x == y)\r\n            return;\r\n        Node prevX = null, currX = head;\r\n        while (currX != null &amp;&amp; currX.data != x) {\r\n            prevX = currX;\r\n            currX = currX.next;\r\n        }\r\n\r\n        Node prevY = null, currY = head;\r\n        while (currY != null &amp;&amp; currY.data != y) {\r\n            prevY = currY;\r\n            currY = currY.next;\r\n        }\r\n        if (currX == null || currY == null)\r\n            return;\r\n\r\n        if (prevX != null)\r\n            prevX.next = currY;\r\n        else \r\n            head = currY;\r\n\r\n        if (prevY != null)\r\n            prevY.next = currX;\r\n        else \r\n            head = currX;\r\n\r\n        Node temp = currX.next;\r\n        currX.next = currY.next;\r\n        currY.next = temp;\r\n    }\r\n\r\n    public void push(int new_data)\r\n    {\r\n        Node new_Node = new Node(new_data);\r\n\r\n        new_Node.next = head;\r\n\r\n        head = new_Node;\r\n    }\r\n\r\n    public void printList()\r\n    {\r\n        Node tNode = head;\r\n        while (tNode != null) {\r\n            System.out.print(tNode.data + &quot; &quot;);\r\n            tNode = tNode.next;\r\n        }\r\n    }\r\n    public static void main(String[] args)\r\n    {\r\n        LinkedList llist = new LinkedList();\r\n        llist.push(5);\r\n        llist.push(4);\r\n        llist.push(3);\r\n        llist.push(2);\r\n        llist.push(1);\r\n\r\n        llist.swapNodes(2, 4);\r\n        llist.printList();\r\n    }\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_3758_4\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"python\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n\r\nclass LinkedList(object):\r\n\tdef __init__(self):\r\n\t\tself.head = None\r\n\r\n\tclass Node(object):\r\n\t\tdef __init__(self, d):\r\n\t\t\tself.data = d\r\n\t\t\tself.next = None\r\n\r\n\tdef swapNodes(self, x, y):\r\n\r\n\t\tif x == y:\r\n\t\t\treturn\r\n\r\n\t\tprevX = None\r\n\t\tcurrX = self.head\r\n\t\twhile currX != None and currX.data != x:\r\n\t\t\tprevX = currX\r\n\t\t\tcurrX = currX.next\r\n\r\n\t\tprevY = None\r\n\t\tcurrY = self.head\r\n\t\twhile currY != None and currY.data != y:\r\n\t\t\tprevY = currY\r\n\t\t\tcurrY = currY.next\r\n\r\n\t\tif currX == None or currY == None:\r\n\t\t\treturn\r\n\t\tif prevX != None:\r\n\t\t\tprevX.next = currY\r\n\t\telse:\r\n\t\t\tself.head = currY\r\n\r\n\t\tif prevY != None:\r\n\t\t\tprevY.next = currX\r\n\t\telse: \r\n\t\t\tself.head = currX\r\n\r\n\t\ttemp = currX.next\r\n\t\tcurrX.next = currY.next\r\n\t\tcurrY.next = temp\r\n\r\n\tdef push(self, new_data):\r\n\r\n\t\tnew_Node = self.Node(new_data)\r\n\t\tnew_Node.next = self.head\r\n\t\tself.head = new_Node\r\n\r\n\tdef printList(self):\r\n\t\ttNode = self.head\r\n\t\twhile tNode != None:\r\n\t\t\tprint(tNode.data , end =&quot; &quot;)\r\n\t\t\ttNode = tNode.next\r\n\r\n\r\nllist = LinkedList()\r\n\r\nllist.push(5)\r\nllist.push(4)\r\nllist.push(3)\r\nllist.push(2)\r\nllist.push(1)\r\nprint(&quot;Linked list before calling swapNodes() &quot;)\r\nllist.printList()\r\nllist.swapNodes(2, 4)\r\nprint(&quot;&#92;nLinked list after calling swapNodes() &quot;)\r\nllist.printList()\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_3758 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_3758 a\"),jQuery(\"#tab-content_3758\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<h4>Output<\/h4>\n<p>1 4 3 2 5<\/p>\n<p><strong>Time Complexity:<\/strong> O(n), where n is the number of nodes present in the LinkedList.<\/p>\n<p><strong>Space Complexity:<\/strong> O(1), no extra space is used.<\/p>\n<h3>Conclusion<\/h3>\n<p>Swapping nodes in a linked list is a fundamental operation that involves exchanging the positions of two nodes within the structure. This process is essential for reorganizing data, sorting the list, or implementing various algorithms without modifying the actual data stored in the nodes. Swapping nodes can be efficiently achieved by changing the links between the nodes rather than swapping their data. By employing this approach, we can efficiently swap nodes in a linked list without the need for extra memory space. This technique is particularly useful when dealing with large data elements or when there is a need for bidirectional traversal within the linked list.<br \/>\n <a href=\"https:\/\/mycode.prepbytes.com\/interview-coding\/practice\/linked-list\">PrepBytes<\/a>.<\/p>\n<table width=\"641\">\n<tbody>\n<tr>\n<td colspan=\"2\" width=\"641\" style=\"text-align: center\"><strong>Related Articles<\/strong><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/doubly-circular-linked-list-introduction-and-insertion\/\">Doubly circular linked list in data structure<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/advantages-disadvantages-and-uses-of-a-doubly-linked-list\/\">Application of doubly linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/applications-of-linked-list-data-structure\/\">Applications of linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/difference-between-a-singly-linked-list-and-a-doubly-linked-list\/\">Singly linked list vs doubly linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/advantage-and-disadvantage-of-linked-list-over-array\/\">Advantages and disadvantages of linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/menu-driven-program-for-all-operations-on-doubly-linked-list-in-c\/\">Doubly linked list all operations in C<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/binary-search\/binary-search-on-linked-list\/\">Binary search in linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/bubble-sort-for-linked-list-by-swapping-nodes\/\">Bubble sort linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/delete-a-node-in-doubly-linked-list\/\">Deletion in doubly linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/delete-middle-of-linked-list\/\">Delete the middle node of a linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/adding-two-polynomials-using-linked-list\/\">Polynomial addition using linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/find-the-smallest-and-largest-elements-in-a-singly-linked-list\/\">Find max value and min value in linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/insert-a-node-at-a-specific-position-in-a-linked-list\/\">Insert a node at a specific position in a linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list-articles\/student-record-management-system-using-linked-list\/\">Student management system using linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/add-two-numbers-represented-by-linked-lists-set-1\/\">Add two numbers represented by linked lists<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/find-the-first-node-of-the-loop-in-a-linked-list\/\">Find starting point of loop in linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/merge-sort-on-a-singly-linked-list\/\">Merge sort linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/delete-a-node-at-a-given-position\/\">Delete a node from linked list at a given position<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/remove-duplicates-from-an-unsorted-linked-list\/\">Remove duplicates from unsorted linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/python\/python-program-to-reverse-a-linked-list\/\">Reverse a linked list in Python<\/a><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>## Frequently Asked Questions (FAQs)<br \/>\nHere are some of the frequently asked questions related to swapping nodes in a linked list<\/p>\n<p>**Q1. What is swapping in data structures?**<br \/>\nSwapping in data structures refers to the process of exchanging the values or positions of two elements within the structure. It is a fundamental operation used to rearrange elements, modify the order, or update the content of nodes in various data structures such as arrays, linked lists, trees, and more. Swapping is commonly employed to reorganize data to achieve a desired arrangement or to facilitate specific algorithms.<\/p>\n<p>**Q2. Explain swapping 2 nodes in linked list**<br \/>\nIn the context of data structures like linked lists, swapping two nodes means interchanging the positions of these nodes. The process involves adjusting the pointers of the adjacent nodes to maintain the integrity of the data structure. Swapping nodes in a linked list can be useful when reordering elements, sorting the list, or implementing algorithms that require rearrangement of elements without changing their values.<\/p>\n<p>**Q3. What is the syntax of the swap() function?**<br \/>\nThe &#8220;swap()&#8221; function is not a standard function available in all programming languages or libraries. Its implementation varies depending on the context and the specific data structure you are working with.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A linked list is a type of data structure that stores a sequence of elements, each of which points to the next element in the sequence. Linked lists are made up of nodes, each of which contains data as well as a pointer to the next node in the sequence. The first node is referred [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[125],"tags":[],"class_list":["post-3757","post","type-post","status-publish","format-standard","hentry","category-linked-list"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Swap Nodes in a Linked List without Swapping Data<\/title>\n<meta name=\"description\" content=\"Learn how can we swap two nodes of a linked list by swapping their link pointers instead of swapping their data.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swap Nodes in a Linked List without Swapping Data\" \/>\n<meta property=\"og:description\" content=\"Learn how can we swap two nodes of a linked list by swapping their link pointers instead of swapping their data.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-08-10T09:27:08+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-07-27T12:44:36+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png\" \/>\n<meta name=\"author\" content=\"PrepBytes\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"PrepBytes\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/\"},\"author\":{\"name\":\"PrepBytes\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e\"},\"headline\":\"Swap Nodes in a Linked List Without Swapping Data\",\"datePublished\":\"2021-08-10T09:27:08+00:00\",\"dateModified\":\"2023-07-27T12:44:36+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/\"},\"wordCount\":1187,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png\",\"articleSection\":[\"Linked list articles\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/\",\"name\":\"Swap Nodes in a Linked List without Swapping Data\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png\",\"datePublished\":\"2021-08-10T09:27:08+00:00\",\"dateModified\":\"2023-07-27T12:44:36+00:00\",\"description\":\"Learn how can we swap two nodes of a linked list by swapping their link pointers instead of swapping their data.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Linked list articles\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/linked-list\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Swap Nodes in a Linked List Without Swapping Data\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e\",\"name\":\"PrepBytes\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g\",\"caption\":\"PrepBytes\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/prepbytes\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Swap Nodes in a Linked List without Swapping Data","description":"Learn how can we swap two nodes of a linked list by swapping their link pointers instead of swapping their data.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/","og_locale":"en_US","og_type":"article","og_title":"Swap Nodes in a Linked List without Swapping Data","og_description":"Learn how can we swap two nodes of a linked list by swapping their link pointers instead of swapping their data.","og_url":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2021-08-10T09:27:08+00:00","article_modified_time":"2023-07-27T12:44:36+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png","type":"","width":"","height":""}],"author":"PrepBytes","twitter_card":"summary_large_image","twitter_misc":{"Written by":"PrepBytes","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/"},"author":{"name":"PrepBytes","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e"},"headline":"Swap Nodes in a Linked List Without Swapping Data","datePublished":"2021-08-10T09:27:08+00:00","dateModified":"2023-07-27T12:44:36+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/"},"wordCount":1187,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png","articleSection":["Linked list articles"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/","url":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/","name":"Swap Nodes in a Linked List without Swapping Data","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png","datePublished":"2021-08-10T09:27:08+00:00","dateModified":"2023-07-27T12:44:36+00:00","description":"Learn how can we swap two nodes of a linked list by swapping their link pointers instead of swapping their data.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926517498-117.Swap%20nodes%20in%20a%20linked%20list%20without%20swapping%20data_Artboard%206.png"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/swap-nodes-in-a-linked-list-without-swapping-data\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Linked list articles","item":"https:\/\/prepbytes.com\/blog\/category\/linked-list\/"},{"@type":"ListItem","position":3,"name":"Swap Nodes in a Linked List Without Swapping Data"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e","name":"PrepBytes","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g","caption":"PrepBytes"},"url":"https:\/\/prepbytes.com\/blog\/author\/prepbytes\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/3757","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=3757"}],"version-history":[{"count":12,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/3757\/revisions"}],"predecessor-version":[{"id":17389,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/3757\/revisions\/17389"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=3757"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=3757"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=3757"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}