TutorialEdge

Challenge 09 - Singly Linked List

:tada: Welcome, everyone to the discussion thread for the 9th Go challenge posted to the site on satisfying interfaces!

Feel free to show us how you solved the challenge by posting your solutions below!

Solution:

package main

import "fmt"

type Element struct {
	Value string
	Next  *Element
}

type SinglyLinkedList struct {
	Count int
	Head  *Element
	Tail  *Element
}

func (l *SinglyLinkedList) Append(value string) {
	// implement
	newElem := &Element{Value: value}
	if l.Size() == 0 {
		l.Head = newElem
		l.Tail = newElem
		l.Count = 1

		return
	} else {
		l.Tail.Next = newElem
		l.Tail = newElem
	}
	l.Count++

}

// You will have to ensure when you add new elements
// that this method still returns the correct value
func (l *SinglyLinkedList) Size() int {
	return l.Count
}

func (l *SinglyLinkedList) Print() {
	current := l.Head
	fmt.Printf("%+v\n", current.Value)
	for current.Next != nil {
		current = current.Next
		fmt.Printf("%+v\n", current.Value)
	}
}

func main() {
	fmt.Println("Singly Linked List Challenge")

	var llist SinglyLinkedList

	values := []string{"First", "Second", "Third"}
	for _, value := range values {
		llist.Append(value)
	}
	llist.Print()
}
package main

import "fmt"

type Element struct {
  Value string
  Next  *Element
}

type SinglyLinkedList struct {
  Count int
  Head  *Element
  Tail  *Element
}

func (l *SinglyLinkedList) Append(value string) {
  newElement := Element{value, nil}
  if l.Count == 0 {
    l.Head = &newElement    
  } else {
  	l.Tail.Next = &newElement
  }
  l.Tail = &newElement
  l.Count++
}

// You will have to ensure when you add new elements
// that this method still returns the correct value
func (l *SinglyLinkedList) Size() int {
  return l.Count
}

func (l *SinglyLinkedList) Print() {
  current := l.Head
  fmt.Printf("%+v\n", current.Value)
  for current.Next != nil {
    fmt.Printf("%+v\n", current.Next.Value)
    current = current.Next
  }
}

func main() {
  fmt.Println("Singly Linked List Challenge")

  var llist SinglyLinkedList

  values := []string{"First", "Second", "Third"}
  for _, value := range values {
    llist.Append(value)
  }
  llist.Print()
}
func (l *SinglyLinkedList) Append(value string) {
	node := Element{value, nil}
	if l.Head == nil {
		l.Head = &node
		l.Tail = &node
		l.Count++
		return
	}
	current := l.Head
	for current.Next != nil {
		current = current.Next
	}
	current.Next = &node
	l.Count++
	l.Tail = &node
}