user3329177
user3329177

Reputation:

linked list beginning and end in python

here my question is i have a linked list of 1->2->3->4->5

my concept is to print them like 1->5->2->4->3

it means first beginning and then end

how can i do it?

i have an idea that is first i take a empty node in empty node i will keep beginning node and

after that i will traverse to last and end node will be kept there at this my brain stops

can anyone guide me to do this? thanks in advance

def mutate_linked_list(head):
   #node creation
   s = t = Node()
   t.next = head
   head = head.next
   while head is None:
        t.next = head
        head = head.next
        # here i used recursion concept
        mutate_linked_list(head)
  return head

but it is not working....

Upvotes: 0

Views: 370

Answers (5)

mgab
mgab

Reputation: 3994

What about:

from itertools import izip_longest
def mutate_linked_list(head):
    m = len(head)/2 # Get the middle position
    return [item for pair in izip_longest(head[:m+1], head[:m:-1])
                 for item in pair
                 if item is not None]

An then, you're ready to go:

head = [1,2,3,4,5]
mutate_linked_list(head)

[1, 5, 2, 4, 3]

It also works with lists with even number of elements...

head = [1,2,3,4,5,6]
mutate_linked_list(head)

[1, 6, 2, 5, 3, 4]

Upvotes: 0

6502
6502

Reputation: 114491

Just as an exercise ...

def mix(head):
    # Walk to the end of the list
    last = head
    secondlast = None
    while last.next:
        secondlast = last
        last = last.next

    if secondlast:
         # move last element to second place
         secondlast.next = None
         last.next = head.next
         head.next = last

         # mix the rest of the list (recursion)
         mix(last.next)

Upvotes: 0

x3al
x3al

Reputation: 586

from collections import deque
def mutate_linked_list(head):
   mydeque = deque(head)
   try:
     while True:
       yield mydeque.popleft()
       yield mydeque.pop()
   except IndexError:
     pass

for i in mutate_linked_list(range(1,6)):
  print(i)

You can obviously do a list and .append to it instead of yielding values.

Upvotes: 0

Eric
Eric

Reputation: 97591

def mutate_linked_list(head):
    # return early for an size 1 list
    if head.next is None:
        return head

    # find the last and penultimate nodes
    penultimate = head
    while penultimate.next.next is not None:
        penultimate = penultimate.next
    last = penultimate.next

    # detach the last node from the end
    penultimate.next = None

    # prepend it to the second node
    last.next = head.next.next

    # and reconnect the head
    head.next = last

    return head

Upvotes: 0

Rémi
Rémi

Reputation: 116

[head[0]]+[head[-1]] + head[1:-1]

Upvotes: 2

Related Questions