def _treeLinkList(self,Node,l): if(len(l)==0): ll=LinkedList() if(Node.getLeftChild()): ll.addNode(Node.getLeftChild()) lChild=True else: print("End of Tree:No more left Child") lChild=False return if(Node.getRightChild()): ll.addNode(Node.getRightChild()) rChild=True else: print("End of Tree:No more right Child") rChild=False return l.append(ll) if(lChild): Node=Node.getLeftChild() self._treeLinkList(Node, l) if(len(l)>0): ll=LinkedList() self.completeTreeLL(l,ll,Node) if(Node.getLeftChild()): Node=Node.getLeftChild() self._treeLinkList(Node, l)
def kthtoLast(l,k): ## If size if known (non recursive solution) n=l.size() if(k>n): print("invalid k") return -1 nl=LinkedList() count=1 current=l.head while(count<=n-k+1 and current !=None): print(current.getData()) nl.addNode(current.getData()) current=current.getNext() count=count+1 return nl
def twoNo(l1,l2): if(l1==None or l1.size()==0): return l2 if(l2==None or l2.size()==0): return l1 n1=no(l1) print("n1 is",n1) n2=no(l2) print("n2 is",n2) n=n1+n2 n=str(n) print("n is",n) l=LinkedList() for item in n: l.addNode(item) l.show() return l
n=l.size() if(k>n): print("invalid k") return -1 nl=LinkedList() count=1 current=l.head while(count<=n-k+1 and current !=None): print(current.getData()) nl.addNode(current.getData()) current=current.getNext() count=count+1 return nl def kthtolastR(l,k): #Using recursion assuming size is unknown if(l==None): return 0 i=kthtolastR(l.getNext(), k)+1 if(i>=k): print(l.getData()) return i l=LinkedList() #random.sample(range(30),10) #[28, 9, 26, 19, 13, 1, 22, 29, 5] for item in [1,2,3,4,5,6,7] : l.addNode(item) l.show() print("Using Recursion") nl=kthtolastR(l.head, 2)
n=n1+n2 n=str(n) print("n is",n) l=LinkedList() for item in n: l.addNode(item) l.show() return l def no(l): current=l.head s="" stack=[] while(current!=None): stack.append(current.getData()) current=current.getNext() while(len(stack)!=0): s=s+str(stack.pop()) return int(s) l1=LinkedList() l2=LinkedList() for item in [6,1,7]: l1.addNode(item) for item in [2,9,5]: l2.addNode(item) twoNo(l1, l2)