From faa363240f81a9a9e4f2b80a9d0af46a6e1d7134 Mon Sep 17 00:00:00 2001 From: Jithendra Yenugula Date: Sun, 23 Dec 2018 12:34:21 +0530 Subject: [PATCH 1/2] Adding a program for swap nodes in linkedlist --- data_structures/linked_list/swapNodes.py | 73 ++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 data_structures/linked_list/swapNodes.py diff --git a/data_structures/linked_list/swapNodes.py b/data_structures/linked_list/swapNodes.py new file mode 100644 index 000000000000..c596e359ac3b --- /dev/null +++ b/data_structures/linked_list/swapNodes.py @@ -0,0 +1,73 @@ +class Node: + def __init__(self, data): + self.data = data; + self.next = None + + +class Linkedlist: + def __init__(self): + self.head = None + + def print_list(self): + temp = self.head + while temp is not None: + print(temp.data) + temp = temp.next + +# adding nodes + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + +# swapping nodes + def swapNodes(self, d1, d2): + if d1 == d2: + return + else: + # find d1 + D1 = self.head + while D1 is not None and D1.data != d1: + prevD1 = D1 + D1 = D1.next + # find d2 + D2 = self.head + while D2 is not None and D2.data != d2: + prevD2 = D2 + D2 = D2.next + if D1 is None and D2 is None: + return + # if D1 is head + if prevD1 is not None: + prevD1.next = D2 + else: + self.head = D2 + # if D2 is head + if prevD2 is not None: + prevD2.next = D1 + else: + self.head = D1 + temp = D1.next + D1.next = D2.next + D2.next = temp + +# swapping code ends here + + + +if __name__ == '__main__': + list = Linkedlist() + list.push(5) + list.push(4) + list.push(3) + list.push(2) + list.push(1) + + list.print_list() + + list.swapNodes(2, 4) + print("After swapping") + list.print_list() + + + From 8adf2477e3290d48480149962b03307d81bf98e1 Mon Sep 17 00:00:00 2001 From: Jithendra Yenugula Date: Tue, 25 Dec 2018 17:09:24 +0530 Subject: [PATCH 2/2] Updating swapNodes --- data_structures/linked_list/swapNodes.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/data_structures/linked_list/swapNodes.py b/data_structures/linked_list/swapNodes.py index c596e359ac3b..ce2543bc46d8 100644 --- a/data_structures/linked_list/swapNodes.py +++ b/data_structures/linked_list/swapNodes.py @@ -22,6 +22,8 @@ def push(self, new_data): # swapping nodes def swapNodes(self, d1, d2): + prevD1 = None + prevD2 = None if d1 == d2: return else: @@ -65,7 +67,7 @@ def swapNodes(self, d1, d2): list.print_list() - list.swapNodes(2, 4) + list.swapNodes(1, 4) print("After swapping") list.print_list()