list-bundle.zc

来自「实现树形结构」· ZC 代码 · 共 104 行

ZC
104
字号
///////////////////////////////////////////////////////////////////////////////
// list - linked list of pointers
///////////////////////////////////////////////////////////////////////////////

import "base/types"
import "collection/collection"
import "memory-bundle"

typedef value = -> void

///////////////////////////////////////////////////////////////////////////////
// List Element
///////////////////////////////////////////////////////////////////////////////

public struct list item: local element
	value: value
end	

//-----------------------------------------------------------------------------
// Enumerating
//-----------------------------------------------------------------------------
public equ each (item: list item)
	def e = item
	while not nil (e)
		def v = value (e)
		yield (v)
		e = next sibling (e): list item
	end
end
	

///////////////////////////////////////////////////////////////////////////////
// List of elements
///////////////////////////////////////////////////////////////////////////////

public struct list

	bundle: memory bundle
	first: list item
	last: list item
	size: size

end

//-----------------------------------------------------------------------------
// Append an element
//-----------------------------------------------------------------------------
public func append (list: list, value: value)

	def e = allocate(bundle (list), sizeof local list item):list item
	
	if not nil (last (list))
		next sibling (last (list)) = e
	end
	
	last (list) = e
	
	if is nil (first (list))
		first (list) = e
	end
	
	// the next is set when inserting in collection
	next sibling (e) = nil
	value (e) = value
	
	++size(list)

end

public equ add (list: list, value: value) = append (list, value)

//-----------------------------------------------------------------------------
// Testing
//-----------------------------------------------------------------------------
equ is empty (list: list) = is nil (first (list))
equ not empty (list: list) = not nil (first (list))

//-----------------------------------------------------------------------------
// Enumerating
//-----------------------------------------------------------------------------
public equ each (list: list)
	def e = first (list)
	while not nil (e)
		def v = value(e)
		yield (v)
		e = next sibling (e): list item
	end
end
	
//-----------------------------------------------------------------------------
// Initialize
//-----------------------------------------------------------------------------
public equ list (bundle: memory bundle, return list: list) = initialize (list, bundle)

public func initialize (list: list, bundle: memory bundle)

	first (list) = nil
	last (list) = nil
	size (list) = 0
	bundle (list) = bundle

end

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?