Пример #1
0
//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
}
Пример #2
0
//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
}