summaryrefslogtreecommitdiff
path: root/go/linkedlist.go
blob: b41b168158a573247481604818217973c7ccc05d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import "fmt"

type node struct {
	v int
	next *node
}

func (head *node) load(N int) {
	if N < 1 {
		return
	}

	for i := 0; i < N-1; i++ {
		fmt.Scanf("%d", &head.v)
		head.next = new(node)
		head = head.next
	}
	fmt.Scanf("%d", &head.v)
	head.next = nil
}

func (head *node) pushTail(val int) {
	for head.next != nil {
		head = head.next
	}

	head.next = new(node)
	head = head.next
	head.v = val
	head.next = nil
}

func (head *node) pushHead(val int) {
	cpnode := &node{
		v: head.v,
		next: head.next,
	}
	head.v = val
	head.next = cpnode
}

func main() {
	lista := new(node)
	lista.next = nil

	lista.load(5)
	lista.pushTail(32)
	lista.pushHead(24)
	for lista != nil {
		fmt.Printf("%d ",lista.v)
		lista = lista.next
	}
}