Example #1
0
func SumLinkedListsReverse(l1, l2 *linkedlist.LinkedList) *linkedlist.LinkedList {
	l1.Reverse()
	l2.Reverse()
	result := SumLinkedLists(l1, l2)
	result.Reverse()
	return result
}
Example #2
0
func PartitionLinkedList(l *linkedlist.LinkedList, x int) {
	var ltroot, lessthan, gtroot, greaterthan *linkedlist.Node

	current := l.Root
	for current != nil {
		if current.Value < x {
			if ltroot == nil || lessthan == nil {
				ltroot = current
				lessthan = current
			} else {
				lessthan.Next = current
				lessthan = lessthan.Next
			}
		} else {
			if gtroot == nil || greaterthan == nil {
				gtroot = current
				greaterthan = current
			} else {
				greaterthan.Next = current
				greaterthan = greaterthan.Next
			}
		}

		current = current.Next
	}

	if l.Root != nil {
		if ltroot != nil && gtroot != nil {
			l.Root = ltroot
			l.Head = greaterthan
			lessthan.Next = gtroot
			greaterthan.Next = nil
		}
	}
}
Example #3
0
// O(n^2)
func RemoveDuplicatesNoStruct(l *linkedlist.LinkedList) {
	var prev *linkedlist.Node
	cur := l.Root
	for cur != nil {
		// for each node we need to iterate through the
		// list and delete all duplicates ahead of it
		RemoveDuplicatesHelper(cur, l, cur.Value)
		prev = cur
		cur = cur.Next
	}

	if prev != nil {
		l.Head = prev
	}
}
Example #4
0
func RemoveDuplicates(l *linkedlist.LinkedList) {
	if l.Length == 0 {
		return
	}

	used := make(map[int]bool, l.Length)

	prev := l.Root
	cur := prev.Next
	used[prev.Value] = true
	for cur != nil {
		if _, dupe := used[cur.Value]; dupe {
			prev.Next = cur.Next
			cur = cur.Next
			l.Length--
		} else {
			used[cur.Value] = true
			prev = cur
			cur = cur.Next
		}
	}

	l.Head = prev
}