Skip to content

enhance swapping code in link #1660

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 14, 2020
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions data_structures/linked_list/swap_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,22 @@ def swapNodes(self, d1, d2):
D1.next = D2.next
D2.next = temp

def swapNodes2(self, d1, d2):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make the method name more expressive

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

swap_nodes_2() would be the proper Python name. See CONTRIBUTING.md. Also please add type hints to the function signature.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using variable names like d1, d2 is probably not a good idea, saving few keystrokes, would result in more heart-strokes for the future :)

if d1 == d2:
return
else:
D1 = self.head
while D1 is not None and D1.data != d1:
D1 = D1.next

D2 = self.head
while D2 is not None and D2.data != d2:
Copy link
Collaborator

@onlinejudge95 onlinejudge95 Jan 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking for None should be done like if D2 or while D2

D2 = D2.next

if D1 is None or D2 is None:
return

D1.data, D2.data = D2.data, D1.data

# swapping code ends here

Expand All @@ -70,3 +86,7 @@ def swapNodes(self, d1, d2):
list.swapNodes(1, 4)
print("After swapping")
list.print_list()

list.swapNodes2(1, 4)
print("After swapping")
list.print_list()