Skip to content

Commit

Permalink
Merge pull request #307 from vaskoz/day145
Browse files Browse the repository at this point in the history
Day145
  • Loading branch information
vaskoz committed Jan 17, 2019
2 parents c77235c + a9121ba commit 27da167
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,5 +154,6 @@ problems from
* [Day 141](https://github.com/vaskoz/dailycodingproblem-go/issues/294)
* [Day 142](https://github.com/vaskoz/dailycodingproblem-go/issues/297)
* [Day 143](https://github.com/vaskoz/dailycodingproblem-go/issues/299)
* [Day 145](https://github.com/vaskoz/dailycodingproblem-go/issues/302)
* [Day 146](https://github.com/vaskoz/dailycodingproblem-go/issues/303)
* [Day 147](https://github.com/vaskoz/dailycodingproblem-go/issues/304)
18 changes: 18 additions & 0 deletions day145/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package day145

// LL is a singly linked list of integers.
type LL struct {
Value int
Next *LL
}

// SwapEveryTwo swaps every two nodes in a linked list.
func SwapEveryTwo(head *LL) *LL {
if head == nil || head.Next == nil {
return head
}
result := head.Next
result.Next, head.Next = head, head.Next.Next
result.Next.Next = SwapEveryTwo(result.Next.Next)
return result
}
42 changes: 42 additions & 0 deletions day145/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package day145

import "testing"

var testcases = []struct {
input, expected *LL
}{
{&LL{1, &LL{2, &LL{3, &LL{4, nil}}}},
&LL{2, &LL{1, &LL{4, &LL{3, nil}}}},
},
{&LL{1, &LL{2, &LL{3, &LL{4, &LL{5, nil}}}}},
&LL{2, &LL{1, &LL{4, &LL{3, &LL{5, nil}}}}},
},
}

func TestSwapEveryTwo(t *testing.T) {
t.Parallel()
for tcid, tc := range testcases {
if result := SwapEveryTwo(tc.input); !equal(result, tc.expected) {
t.Errorf("TCID%d do not match", tcid)
}
}
}

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

func equal(one, two *LL) bool {
for one != nil && two != nil {
if one.Value != two.Value {
return false
}
one = one.Next
two = two.Next
}
return one == nil && two == nil
}

0 comments on commit 27da167

Please sign in to comment.