简体   繁体   中英

Return Sublist of Singly Linked List Recursively

I am trying to return the sublist of a singly linked list recursively.

Ex. list = 3->4->5->None

sub(list, 1, 2) should return 4->5

param 1 - start index

param 2 - length of sublist

I am having a little trouble as my code only returns the last element of the sublist and not the whole sublist.

def sub(list, start, length) -> Node:
    if list is None:
        return None
    elif start <= 0:
        if length ==1:
            list.next = None
            return list
        else:
            return sub(list.next, start - 1, length - 1)
    else:

        return sub(list.next, start - 1, length)

You can use a parameter in your sub function that stores the accumulated sub list as you traverse the main structure:

def sub(lst, s, e, c = 0, new_l = None):
   if c >= e:
      return new_l
   if lst is None:
      raise IndexError('index out of bounds')
   return sub(lst.next, s, e, c = c+1, new_l = None if c + 1 <= s else getattr(new_l, 'add_node', Lst)(lst.value))

Lst implemenation:

class Lst:
   def __init__(self, val=None):
      self.value, self.next = val, None
   def add_node(self, val):
      if self.value is None:
         self.value = val
      elif self.next is None:
         self.next = Lst(val)
      else:
         self.next.add_node(val)
      return self
   def __repr__(self):
      return f'{self.value}{"" if self.next is None else " -> "+repr(self.next)}'


l = Lst()
for i in range(10):
   l.add_node(i)

print(sub(l, 0, 4))
print(sub(l, 2, 7))
print(sub(l, 5, 12))

Output:

0 -> 1 -> 2 -> 3
2 -> 3 -> 4 -> 5 -> 6
  File "<stdin>", line 6, in sub
  [Previous line repeated 7 more times]
File "<stdin>", line 5, in sub
IndexError: index out of bounds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM