Skip to content

Commit

Permalink
Merge d214472 into 3955911
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Nov 3, 2018
2 parents 3955911 + d214472 commit d8db7a6
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,4 @@ problems from
* [Day 70](https://github.com/vaskoz/dailycodingproblem-go/issues/149)
* [Day 71](https://github.com/vaskoz/dailycodingproblem-go/issues/151)
* [Day 72](https://github.com/vaskoz/dailycodingproblem-go/issues/153)
* [Day 73](https://github.com/vaskoz/dailycodingproblem-go/issues/155)
20 changes: 20 additions & 0 deletions day73/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package day73

// SinglyLL represents a node in a singly linked list.
type SinglyLL struct {
Value interface{}
Next *SinglyLL
}

// ReverseSinglyLinkedList reverses a singly linked list in O(1) space
// and O(N) time.
func ReverseSinglyLinkedList(head *SinglyLL) *SinglyLL {
var reversed *SinglyLL
for head != nil {
next := head.Next
head.Next = reversed
reversed = head
head = next
}
return reversed
}
50 changes: 50 additions & 0 deletions day73/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package day73

import "testing"

var testcases = []struct {
input []interface{}
}{
{[]interface{}{"first", 2, "third", 4, "fifth", 6}},
{[]interface{}{"foo", "bar", "baz"}},
{[]interface{}{1, 2, 3}},
}

func createSinglyLL(data []interface{}) *SinglyLL {
head := &SinglyLL{}
current := head
for _, value := range data {
current.Next = &SinglyLL{Value: value, Next: nil}
current = current.Next
}
return head.Next
}

func wasReversed(head *SinglyLL, data []interface{}) bool {
for i := range data {
if head == nil || head.Value != data[len(data)-1-i] {
return false
}
head = head.Next
}
return head == nil
}

func TestReverseSinglyLinkedList(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
sll := createSinglyLL(tc.input)
if reversed := ReverseSinglyLinkedList(sll); !wasReversed(reversed, tc.input) {
t.Errorf("This list was not reversed correctly: %v", tc.input)
}
}
}

func BenchmarkReverseSinglyLinkedList(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
sll := createSinglyLL(tc.input)
ReverseSinglyLinkedList(sll)
}
}
}

0 comments on commit d8db7a6

Please sign in to comment.