Linked lists Challenge

Download exercises zip

Browse files online

Open linked_chal.py with a text editor and implement the following methods

rshift

def rshift(self, el):
    """ Shifts toward right the *data* of all nodes by one,
        writing el as data in first node and finally
        RETURN the data that was in last node

        - if list is empty, raises ValueError

        - DO NOT create new nodes nor rearrange links
        - ONLY write node *data*
        - MUST execute in O(n) where n is the list size
    """

Testing: python3 -m unittest linked_chal_test.RShiftTest

[1]:
from linked_chal_sol import *

ll = LinkedList()
ll.add('a')
ll.add('d')
ll.add('a')
ll.add('c')
ll.add('b')
ll.add('d')
ll.add('e')

[2]:
ll.rshift('p')
[2]:
'a'
[3]:
print(ll)
LinkedList: p,e,d,b,c,a,d
[4]:
ll.rshift('q')
[4]:
'd'
[5]:
print(ll)
LinkedList: q,p,e,d,b,c,a
[6]:
ll.rshift('r')
[6]:
'a'
[7]:
print(ll)
LinkedList: r,q,p,e,d,b,c
[8]:
ll.rshift('s')
ll.rshift('t')
ll.rshift('u')
ll.rshift('v')
ll.rshift('z')
[8]:
'p'
[9]:
print(ll)
LinkedList: z,v,u,t,s,r,q

lshift

Implement shifting toward the left:

def lshift(self, el):
        """ Shifts toward left the *data* of all nodes by one,
            writing el as data in last node and finally
            RETURN the data that was in first node

            - if list is empty, raises ValueError

            - DO NOT create new nodes nor rearrange links
            - ONLY write node *data*
            - MUST execute in O(n) where n is the list size
        """
[10]:
ll = LinkedList()
ll.add('a')
ll.add('d')
ll.add('a')
ll.add('c')
ll.add('b')
ll.add('d')
ll.add('e')

print(ll)
LinkedList: e,d,b,c,a,d,a
[11]:
ll.lshift('p')
[11]:
'e'
[12]:
print(ll)
LinkedList: d,b,c,a,d,a,p
[13]:
ll.lshift('q')
[13]:
'd'
[14]:
print(ll)
LinkedList: b,c,a,d,a,p,q
[15]:
ll.lshift('r')
ll.lshift('s')
ll.lshift('t')
ll.lshift('u')
ll.lshift('v')
ll.lshift('z')
[15]:
'p'
[16]:
print(ll)
LinkedList: q,r,s,t,u,v,z
[ ]: