diff options
author | Santo Cariotti <sancn@live.com> | 2017-09-30 15:19:48 +0200 |
---|---|---|
committer | Santo Cariotti <sancn@live.com> | 2017-09-30 15:19:48 +0200 |
commit | 2ef23aff47ea0b9c1ad26a80e6b3ce90dc2ce4ad (patch) | |
tree | 10bc4b1a2f6ca99e36230d0da24b0d2d8018b732 | |
parent | 26c5b163994229424f2873f54fafac845759f371 (diff) |
modified linkedlist
-rw-r--r-- | go/linkedlist.go | 93 |
1 files changed, 63 insertions, 30 deletions
diff --git a/go/linkedlist.go b/go/linkedlist.go index b41b168..8b827f3 100644 --- a/go/linkedlist.go +++ b/go/linkedlist.go @@ -7,49 +7,82 @@ type node struct { next *node } -func (head *node) load(N int) { - if N < 1 { - return +var head *node = nil + +func (l *node) pushH(val int) *node { + if head == nil { + l.v = val + l.next = nil + head = l + return l + } else { + nnode := new(node) + nnode = head + + nnode2 := &node { + v: val, + next: nnode, + } + head = nnode2 + return head } +} - for i := 0; i < N-1; i++ { - fmt.Scanf("%d", &head.v) - head.next = new(node) - head = head.next +func (l *node) pushT(val int) *node { + if head == nil { + l.v = val + l.next = nil + head = l + return l + } else { + for l.next != nil { + l = l.next + } + + l.next = new(node) + l.next.v = val + l.next.next = nil + return l } - fmt.Scanf("%d", &head.v) - head.next = nil } -func (head *node) pushTail(val int) { - for head.next != nil { - head = head.next +func (l *node) popH() *node { + if head == nil { + return head } - head.next = new(node) - head = head.next - head.v = val - head.next = nil + cpnode := new(node) + cpnode = head.next + head = cpnode + + return head } -func (head *node) pushHead(val int) { - cpnode := &node{ - v: head.v, - next: head.next, +func (l *node) popT() *node { + if head == nil { + return head + } + + cpnode := new(node) + cpnode = head + + for cpnode.next.next != nil { + cpnode = cpnode.next } - head.v = val - head.next = cpnode + + cpnode.next = nil + return head } 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 + lista.pushT(25).pushT(24).pushT(32) + lista.pushT(56) + lista.pushH(36) + lista.popH() + lista.popT() + for head != nil { + fmt.Printf("%d ",head.v) + head = head.next } } |