Exemple #1
0
// Gives sliced linked list from kth element to last element.
// Also it assumes that, we don't know size&last element of the linkedlist.
func Slice(l datastructures.LinkedList, kth int) *datastructures.LinkedList {
	if kth <= 0 {
		return nil
	}
	current := l.Head()
	runner := current
	sliced_list := datastructures.LinkedList{}
	count := 0
	for current != nil {
		runner = current
		if count == kth {
			sliced_list.SetHead(current)
			for runner != nil {
				runner = runner.Next()
			}
			break
			sliced_list.SetTail(current)
		}
		count++
		current = current.Next()
	}
	if sliced_list.Head() != nil {
		return &sliced_list
	} else {
		return nil
	}
}
Exemple #2
0
// reverse given list
func reverseList(l ds.LinkedList) ds.LinkedList {
	temp := l.Copy()
	reversed_list := ds.LinkedList{}
	head := temp.Head()
	current_node := head
	var prev_node *ds.Node
	for {
		if current_node != nil {
			next_node := current_node.Next()
			current_node.SetNext(prev_node)
			prev_node = current_node
			current_node = next_node
		} else {
			reversed_list.SetHead(prev_node)
			break
		}
	}
	return reversed_list
}