def test_create_partition():
    list1 = LinkedList()
    list1.addNode(3)
    list1.addNode(1)
    list1.addNode(2)
    create_partition(list1, 2)
    assert list1.head.value == 1
    assert list1.head.next.value == 2
    assert list1.head.next.next.value == 3
def test_remove_dups():
    list1 = LinkedList()
    list1.addNode("peanut")
    list1.addNode("davey")
    list1.addNode("dog")
    list1.addNode("peanut")
    list1.addNode("hearts")
    list1.addNode("dog")
    remove_dups(list1)
    assert list1.head.next.next.next.value == "hearts"
예제 #3
0
from linked_list import LinkedList
# import linked_list will get all top level functionality, then you gotta do linked_list.LinkedList
import linked_list
list = LinkedList()
list.addNode(5)
list.addNode(4)
list.addNode(3)
list.addNode(5)
list.printList()


# given an unsorted linked list, remove the duplicates
# eg: 5->4->3->5 
# after remove dup: 5->4->3

# as we go through the list, keep track of numbers seen in a dictionary (hashtable)
# note if the data were chars, we could potentially just have an array

def removeDups(list):
	curr = list.head
	elements = {}
	# no special case for head element, can't have dups with only 1 element
	elements[curr.data] = True
	prev = curr	
	curr = curr.next
	
	while curr != None:
		key = curr.data
		if key in elements:
			prev.next = curr.next # removes curr
		else:
from linked_list import LinkedList

# find kth to last element of a singly linked list
# Second to last = 2nd to last 
# 1st to last = last

list = LinkedList()
list.addNode(1)
list.addNode(2)
list.addNode(3)
list.addNode(4)
list.addNode(5)
list.addNode(6)
list.printList()

# we can run through the linked list to grab the size, N.
# Linked list elements are indexed 0, 1, ... N-1
# kth to last element. 
# 1st to last element = last element. = N - 1
# 2nd to last element = N - 2
# Nth to last element = N - N = 0 = first element

def get_kth_to_last(list, k):
	curr = list.head
	num_elements = 0
	while curr != None:
		curr = curr.next
		num_elements+=1
	index_we_want = num_elements - k
	if index_we_want < 0:
		return None
예제 #5
0
    ll.head = previousnode
    

#recursive solution
def recReverse(ll, node):
    if node.next == None:
        ll.head = node
        return
    
    recReverse(ll, node.next)
    temp = node.next
    temp.next = node
    node.next = None
    


if __name__ == "__main__":
    ll = LinkedList()
    nodes = [1,2,3,4,5,6]

    for i in nodes:
        node = Node(i)
        ll.addNode(node)
        
    print(ll.print_list())
    
    iterReverse(ll)
    print(ll.print_list())
    
    recReverse(ll, ll.head)
    print(ll.print_list())