Problem Complete the function swapNodesLinkedList() to take in the first node of
ID: 3719941 • Letter: P
Question
Problem
Complete the function swapNodesLinkedList() to take in the first node of a Linked List and two indices, i1 and i2, and swap the nodes at those indices.
Your function should not return anything, simply swap the values of the given LinkedList.
Example
list: 100 -> 85 -> 75 -> 65
swapNodesLinkedList(list, 0, 3)
# returns 65 -> 85 -> 75 -> 100
Code:
class Node:
def __init__(self, value):
self.value = value
self.next = None
def swapNodesLinkedList(first, i1, i2):
# TODO
?
Explanation / Answer
class Node: def __init__(self, value): self.value = value self.next = None def swapNodesLinkedList(first, i1, i2): i = 0 temp = first n1 = None n2 = None while temp is not None: if i == i1: n1 = temp elif i == i2: n2 = temp temp = temp.next i += 1 if n1 is not None and n2 is None: n1.temp, n2.temp = n2.temp, n1.temp
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.