So I have a linked list a->b->c->d(adsbygoogle = window.adsbygoogle || []).push({});

and I want to make another list

b->a->d->c

in a systematic way by interchanging pointers. But for some reason it isn't working. All I did was move the link between b and c into b to a. Then the link from a to b, changed to a to d. Then the one connecting c to d is reversed. I'm not sure what went wrong.

Code (Python):

class ListNode(object):

def __init__(self, x):

self.val = x

self.next = None

A=['a','b','c','d']

head=ListNode(A[0])

#filling the linked list with abcd

temp=head

for i in A[1:]:

temp.next=ListNode(i)

temp=temp.next

point=head

print("the current linked list")

while(point):

print(point.val)

point=point.next

print(" ")

#attempting to alter the list

Temp1=head.next.next

head.next.next=head # moving the link between b-c to a

Temp2=head.next

head.next=head.next.next.next #moving the link between a-b to d

head.next.next.next=Temp1 #moving the link between d and c

head=Temp2

#print(head)

print("the new linkedlist")

point=head

while(point):

print(point.val)

point=point.next

The output is

the current linked list

a

b

c

d

the new linkedlist

b

a

c

d

**Physics Forums | Science Articles, Homework Help, Discussion**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# Python Switching the links in a linked list

Have something to add?

Draft saved
Draft deleted

**Physics Forums | Science Articles, Homework Help, Discussion**