//recursive function to find the kth from last element func findKFromLastRecr(head *list.Element, k int, wrapper *WrapObj) *list.Element { if head == nil { return nil } resNode := findKFromLastRecr(head.Next(), k, wrapper) //Increment the count on every return call wrapper.count = (wrapper.count) + 1 if wrapper.count == k { return head } return resNode }
//Iterative function to find the kth from last element func findKFromLast(l *list.List, k int) *list.Element { size := l.Len() //Base condition. If the size of the list is less than k then kth element cannot be found if size < k { return nil } var elem *list.Element elem = l.Front() for i := 1; i < k; i++ { elem = elem.Next() } var first *list.Element for first = l.Front(); first != nil && elem != nil; elem, first = elem.Next(), first.Next() { //return the current node when current+k position is nil if elem.Next() == nil { return first } } return nil }
func findLoopsInList(l *list.List) *list.Element { if l == nil { return nil } var head *list.Element var slow *list.Element var fast *list.Element head = l.Front() for slow, fast = l.Front(), l.Front(); slow != nil && fast != nil; slow, fast = slow.Next(), fast.Next().Next() { if slow == fast { break } } if fast == nil || fast.Next() == nil { return nil } slow = head for slow != fast { slow = slow.Next() fast = fast.Next() } return fast }
//Function to add the list func addLists(l *list.List, m *list.List) *list.List { if l == nil && m == nil { return nil } lLength := l.Len() mLength := m.Len() carry := 0 value := 0 resList := list.New() var e *list.Element var f *list.Element for e, f = l.Front(), m.Front(); e != nil && f != nil; e, f = e.Next(), f.Next() { value = carry + e.Value.(int) + f.Value.(int) //get the carry and value carry = 0 carry = value / 10 value = value % 10 resList.PushFront(value) } //To identify the long list if the size is different var p *list.Element if lLength > mLength { p = e } else { p = f } for ; p != nil; p = p.Next() { value = carry + p.Value.(int) carry = 0 carry = value / 10 value = value % 10 resList.PushFront(value) } if carry != 0 { resList.PushFront(carry) } return resList }