{"id":26937,"date":"2017-12-28T21:45:03","date_gmt":"2017-12-28T16:15:03","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26937"},"modified":"2018-10-30T17:02:42","modified_gmt":"2018-10-30T11:32:42","slug":"python-algorithm-swap-nodes-linked-list-without-swapping-data","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-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\/technology\/python-algorithm-find-length-linked-list-iterative-recursive\/\" target=\"_blank\" rel=\"noopener\">linked list<\/a> and two keys in it, <a href=\"https:\/\/www.wikitechy.com\/technology\/python-algorithm-pairwise-swap-elements-given-linked-list\/\" target=\"_blank\" rel=\"noopener\">swap nodes<\/a> for two given keys. Nodes should be swapped by changing links. Swapping 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: #000080;\"><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>How to write a clean working code that handles all of the above possibilities.<\/p>\n<p>The idea it to first search x and y in given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers. Following <a href=\"https:\/\/www.wikitechy.com\/tutorials\/python\/python-program-to-reverse-a-number\" target=\"_blank\" rel=\"noopener\">python<\/a> implementation of this approach.<\/p>\n<h3 id=\"python-programming\"><span style=\"color: #333399;\"><strong>Python Programming:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program to swap two given nodes of a linked list<br\/>class LinkedList(object):<br\/>    def __init__(self):<br\/>        self.head = None<br\/> <br\/>    # head of list<br\/>    class Node(object):<br\/>        def __init__(self, d):<br\/>            self.data = d<br\/>            self.next = None<br\/> <br\/>    # Function to swap Nodes x and y in linked list by<br\/>    # changing links<br\/>    def swapNodes(self, x, y):<br\/> <br\/>        # Nothing to do if x and y are same<br\/>        if x == y:<br\/>            return<br\/> <br\/>        # Search for x (keep track of prevX and CurrX)<br\/>        prevX = None<br\/>        currX = self.head<br\/>        while currX != None and currX.data != x:<br\/>            prevX = currX<br\/>            currX = currX.next<br\/> <br\/>        # Search for y (keep track of prevY and currY)<br\/>        prevY = None<br\/>        currY = self.head<br\/>        while currY != None and currY.data != y:<br\/>            prevY = currY<br\/>            currY = currY.next<br\/> <br\/>        # If either x or y is not present, nothing to do<br\/>        if currX == None or currY == None:<br\/>            return<br\/>        # If x is not head of linked list<br\/>        if prevX != None:<br\/>            prevX.next = currY<br\/>        else: #make y the new head<br\/>            self.head = currY<br\/> <br\/>        # If y is not head of linked list<br\/>        if prevY != None:<br\/>            prevY.next = currX<br\/>        else: # make x the new head<br\/>            self.head = currX<br\/> <br\/>        # Swap next pointers<br\/>        temp = currX.next<br\/>        currX.next = currY.next<br\/>        currY.next = temp<br\/> <br\/>    # Function to add Node at beginning of list.<br\/>    def push(self, new_data):<br\/> <br\/>        # 1. alloc the Node and put the data<br\/>        new_Node = self.Node(new_data)<br\/> <br\/>        # 2. Make next of new Node as head<br\/>        new_Node.next = self.head<br\/> <br\/>        # 3. Move the head to point to new Node<br\/>        self.head = new_Node<br\/> <br\/>    # This function prints contents of linked list starting<br\/>    # from the given Node<br\/>    def printList(self):<br\/>        tNode = self.head<br\/>        while tNode != None:<br\/>            print tNode.data,<br\/>            tNode = tNode.next<br\/> <br\/># Driver program to test above function<br\/>llist = 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\/>print &quot;Linked list before calling swapNodes() &quot;<br\/>llist.printList()<br\/>llist.swapNodes(4, 3)<br\/>print &quot;\\nLinked list after calling swapNodes() &quot;<br\/>llist.printList()<br\/> <br\/># This code is contributed by BHAVYA JAIN<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre> Linked list before calling swapNodes() \r\n  1 2 3 4 5 6 7\r\n Linked list after calling swapNodes() \r\n  1 2 4 3 5 6 7<\/pre>\n<p><span style=\"color: #0000ff;\"><strong>Optimizations:<\/strong> <\/span>The above code can be optimized to search x and y in single traversal. Two <a href=\"https:\/\/www.wikitechy.com\/tutorials\/python\/python-loop\" 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>Python 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":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79476,4148,79478],"tags":[80425,80422,80431,80424,80427,80423,80428,80430,80426,80420,80429,80421],"class_list":["post-26937","post","type-post","status-publish","format-standard","hentry","category-linked-list","category-python","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\/26937","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=26937"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26937\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26937"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26937"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26937"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}