{"id":26936,"date":"2017-12-28T21:43:36","date_gmt":"2017-12-28T16:13:36","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26936"},"modified":"2018-10-29T10:51:20","modified_gmt":"2018-10-29T05:21:20","slug":"java-algorithm-swap-nodes-linked-list-without-swapping-data","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-swap-nodes-linked-list-without-swapping-data\/","title":{"rendered":"Swap nodes in a linked list without swapping data"},"content":{"rendered":"<p>Given a <a href=\"https:\/\/www.wikitechy.com\/tutorials\/java\/java-linked-list\" target=\"_blank\" rel=\"noopener\">linked list<\/a> and two keys in it, <strong>swap nodes for two given keys<\/strong>. Nodes should be swapped by changing links. <a href=\"https:\/\/www.wikitechy.com\/technology\/java-algorithm-pairwise-swap-elements-given-linked-list\/\" target=\"_blank\" rel=\"noopener\">Swapping<\/a> data of nodes may be expensive in many situations when data contains many fields.<span id=\"more-134695\"><\/span><\/p>\n<p>It may be assumed that all keys in linked list are distinct.<\/p>\n<h3 id=\"examples\"><span style=\"color: #800000;\"><strong>Examples:<\/strong><\/span><\/h3>\n<pre>Input:  10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14,  x = 12, y = 20\r\nOutput: 10-&gt;15-&gt;20-&gt;13-&gt;12-&gt;14\r\n\r\nInput:  10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14,  x = 10, y = 20\r\nOutput: 20-&gt;15-&gt;12-&gt;13-&gt;10-&gt;14\r\n\r\nInput:  10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14,  x = 12, y = 13\r\nOutput: 10-&gt;15-&gt;13-&gt;12-&gt;20-&gt;14<\/pre>\n<p>This may look a simple problem, but is interesting question as it has following cases to be handled.<br \/>\n1) x and y may or may not be adjacent.<br \/>\n2) Either x or y may be a head node.<br \/>\n3) Either x or y may be last node.<br \/>\n4) x and\/or y may not be present in linked list.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Let us write a clear working code that handles all the above cases:<\/p>\n<p>The idea is to first search x and y in given <a href=\"https:\/\/www.wikitechy.com\/technology\/java-algorithm-find-middle-given-linked-list\/\" target=\"_blank\" rel=\"noopener\">linked list<\/a>. If any of them is not present, then return. While searching for x and y, keep track of <strong>current and previous pointers<\/strong>. First change next of previous pointers, then change next of current pointers. Following is <a href=\"https:\/\/www.wikitechy.com\/tutorials\/java\/java-tutorial\" target=\"_blank\" rel=\"noopener\">Java<\/a> implementation of this approach.<\/p>\n<h3 id=\"java-programming-for-swap-nodes-in-a-linked-list\"><span style=\"color: #003366;\"><strong>Java Programming For Swap Nodes in a Linked List:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to swap two given nodes of a linked list<br\/> <br\/>class Node<br\/>{<br\/>    int data;<br\/>    Node next;<br\/>    Node(int d)<br\/>    {<br\/>        data = d;<br\/>        next = null;<br\/>    }<br\/>}<br\/> <br\/>class LinkedList<br\/>{<br\/>    Node head; \/\/ head of list<br\/> <br\/>    \/* Function to swap Nodes x and y in linked list by<br\/>       changing links *\/<br\/>    public void swapNodes(int x, int y)<br\/>    {<br\/>        \/\/ Nothing to do if x and y are same<br\/>        if (x == y) return;<br\/> <br\/>        \/\/ Search for x (keep track of prevX and CurrX)<br\/>        Node prevX = null, currX = head;<br\/>        while (currX != null &amp;&amp; currX.data != x)<br\/>        {<br\/>            prevX = currX;<br\/>            currX = currX.next;<br\/>        }<br\/> <br\/>        \/\/ Search for y (keep track of prevY and currY)<br\/>        Node prevY = null, currY = head;<br\/>        while (currY != null &amp;&amp; currY.data != y)<br\/>        {<br\/>            prevY = currY;<br\/>            currY = currY.next;<br\/>        }<br\/> <br\/>        \/\/ If either x or y is not present, nothing to do<br\/>        if (currX == null || currY == null)<br\/>            return;<br\/> <br\/>        \/\/ If x is not head of linked list<br\/>        if (prevX != null)<br\/>            prevX.next = currY;<br\/>        else \/\/make y the new head<br\/>            head = currY;<br\/> <br\/>        \/\/ If y is not head of linked list<br\/>        if (prevY != null)<br\/>            prevY.next = currX;<br\/>        else \/\/ make x the new head<br\/>            head = currX;<br\/>        Node temp = currX.next;<br\/>        currX.next = currY.next;<br\/>        currY.next = temp;<br\/>    }<br\/> <br\/>    \/* Function to add Node at beginning of list. *\/<br\/>    public void push(int new_data)<br\/>    {<br\/>        <br\/>        Node new_Node = new Node(new_data);<br\/> <br\/>        new_Node.next = head;<br\/> <br\/> <br\/>        head = new_Node;<br\/>    }<br\/> <br\/>    public void printList()<br\/>    {<br\/>        Node tNode = head;<br\/>        while (tNode != null)<br\/>        {<br\/>            System.out.print(tNode.data+&quot; &quot;);<br\/>            tNode = tNode.next;<br\/>        }<br\/>    }<br\/> <br\/>    <br\/>    public static void main(String[] args)<br\/>    {<br\/>        LinkedList llist = new LinkedList();<br\/> <br\/>        \/* The constructed linked list is:<br\/>            1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7 *\/<br\/>        llist.push(7);<br\/>        llist.push(6);<br\/>        llist.push(5);<br\/>        llist.push(4);<br\/>        llist.push(3);<br\/>        llist.push(2);<br\/>        llist.push(1);<br\/> <br\/>        System.out.print(&quot;\\n Linked list before calling swapNodes() &quot;);<br\/>        llist.printList();<br\/> <br\/>        llist.swapNodes(4, 3);<br\/> <br\/>        System.out.print(&quot;\\n Linked list after calling swapNodes() &quot;);<br\/>        llist.printList();<br\/>    }<br\/>}<br\/>\/\/ This code is contributed by Rajat Mishra<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre> Linked list before calling swapNodes() 1 2 3 4 5 6 7\r\n Linked list after calling swapNodes() 1 2 4 3 5 6 7<\/pre>\n<h3 id=\"optimizations\"><span style=\"color: #0000ff;\"><strong>Optimizations:<\/strong> <\/span><\/h3>\n<p>The code can be optimized to search x and y in single traversal. Two <a href=\"https:\/\/www.wikitechy.com\/tutorials\/java\/loops-in-java\" target=\"_blank\" rel=\"noopener\">loops<\/a> are used to keep program simple.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Swap nodes in a linked list without swapping data &#8211; Linked List &#8211; Given a linked list and two keys in it, swap nodes for two given keys<\/p>\n","protected":false},"author":1,"featured_media":31615,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79476,79478],"tags":[80425,80422,80431,80424,80427,80423,80428,80430,80426,80420,80429,80421],"class_list":["post-26936","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linked-list","category-singly-linked-list","tag-how-to-swap-two-nodes-in-a-doubly-linked-list-java","tag-swap-adjacent-nodes-in-linked-list","tag-swap-adjacent-nodes-in-linked-list-java","tag-swap-alternate-nodes-linked-list","tag-swap-kth-node-from-beginning-with-kth-node-from-end-in-a-linked-list","tag-swap-nodes-doubly-linked-list","tag-swap-nodes-in-doubly-linked-list-java","tag-swap-nodes-in-linked-list","tag-swap-two-adjacent-elements-linked-list-java","tag-swap-two-nodes-in-a-linked-list-java","tag-swapping-two-nodes-in-a-doubly-linked-list-c","tag-write-a-program-to-reverse-a-linked-list"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26936","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26936"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26936\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31615"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26936"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26936"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26936"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}