示例#1
0
文件: 2.2.go 项目: muraty/ctci
// 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
	}
}
示例#2
0
文件: 2.4.go 项目: muraty/ctci
// partition given list into two parts due to the given value
// and then merge them together.
func PartitionList(l datastructures.LinkedList, value int) datastructures.LinkedList {
	beforeValue := datastructures.LinkedList{}
	afterValue := datastructures.LinkedList{}

	head := l.Head()
	for head != nil {
		n := datastructures.Node{}
		n.SetValue(head.GetValue())
		if head.GetValue() < value {
			beforeValue.Add(&n)
		} else {
			afterValue.Add(&n)
		}
		head = head.Next()
	}
	beforeValue.SetTail(afterValue.Head())
	return beforeValue
}