Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import "fmt"
- func main() {
- list := List{}
- list.insert(2)
- list.insert(4)
- list.insert(6)
- list.printListInfo()
- }
- // Node Type
- type Node struct {
- data int
- next *Node
- }
- // LinkedList Type
- type List struct {
- head *Node
- }
- func (self *List) printListInfo() {
- fmt.Println("\nList Info:")
- fmt.Printf("items: %v\n", self.items())
- fmt.Printf("count: %v\n", self.count())
- fmt.Println("\n")
- }
- func (l *List) insert(n int) {
- if l.head == nil {
- l.head = &Node{ n, l.head }
- } else {
- temp := l.head
- last := l.head
- for temp != nil {
- last = temp
- temp = temp.next
- }
- last.next = &Node { n, nil }
- }
- l.printNodes()
- }
- func (l *List) printNodes() {
- temp := l.head
- for temp != nil {
- fmt.Printf("%v ", temp.data)
- temp = temp.next
- }
- fmt.Println()
- }
- func (l *List) count() int {
- temp := l.head
- count := 0
- for temp != nil {
- count += 1
- temp = temp.next
- }
- return count
- }
- func (l *List) items() []int {
- temp := l.head
- var nodes []int
- for temp != nil {
- nodes = append(nodes, temp.data)
- temp = temp.next
- }
- return nodes
- }
Add Comment
Please, Sign In to add comment