-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #307 from vaskoz/day145
Day145
- Loading branch information
Showing
3 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |