Skip to content Skip to sidebar Skip to footer

How To Switch Nodes At An Index With The Head Of A List?

I'm currently trying to create a function that will switch the nodes at index with the head of the list. So if my list (list) has the values [1, 7, 9, 12] and I call switch(list, 2

Solution 1:

Switching elements in a list is actually very easy:

myList[0], myList[1] = myList[1], myList[0]

This will swap the first and second elements in myList, in place. Python actually has an optimized bytecode command that very quickly swaps two values on the program stack, so this is about as fast as you can swap list values.

Of course, in that case you wouldn't be returning a new list, you'd be modifying the old one. So instead of myList = switch(myList, 2), you would just write switch(myList, 2). The code would look something like this:

def switch(lst, i):
  lst[0], lst[i] = lst[i], lst[0]

If you want to return an entirely new list, you'd need to make a copy first:

def switch(lst, i):
  newlst =list(lst)
  newlst[0], newlst[i] = newlst[i], newlst[0]
  return newlst

EDIT: if you're working with a linked list, that is a bit of a different story. I don't think Python optimizations exist for linked lists; regular lists are very easy to add items to, and they work with any kind of object, so linked lists very much lose their purpose in Python. Nevertheless, here's a suggestion:

defswitch(ll, i):
  head = ll
  currentItem = ll      # The head again
  prevItem = None# The item that links to tempItemfor x inrange(i):    # Find the item to swap
    prevItem = currentItem
    currentItem = currentItem.next# Now we swap. We're rotating three items' .next values, so we can't# do the really optimized way.
  temp = currentItem.next
  currentItem.next = head.next
  head.next = prevItem.next
  prevItem.next = temp

Linked list manipulation is all about maintaining proper links to the next item. Also note that the above code will fail if you're trying to swap for a position that doesn't actually exist in your linked list. Check your inputs.

Solution 2:

You can do it the same way you would switch two variables:

defswitch(x, ix):
    # x = x[:]
    x[0], x[ix] = x[ix], x[0]
    # return x

This will modify the existing list. If you want to return a new list, uncomment the commented lines.

Post a Comment for "How To Switch Nodes At An Index With The Head Of A List?"