Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5328f9f

Browse files
committed
Add: Palindrome Linked List
1 parent d9bca6f commit 5328f9f

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,28 @@
11
package palindrome_linked_list
2+
3+
import . "github.com/openset/leetcode/internal/kit"
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* type ListNode struct {
8+
* Val int
9+
* Next *ListNode
10+
* }
11+
*/
12+
func isPalindrome(head *ListNode) bool {
13+
var prev *ListNode
14+
slow, fast := head, head
15+
for fast != nil && fast.Next != nil {
16+
slow, fast = slow.Next, fast.Next.Next
17+
}
18+
for slow != nil {
19+
prev, slow, slow.Next = slow, slow.Next, prev
20+
}
21+
for head != nil && prev != nil {
22+
if head.Val != prev.Val {
23+
return false
24+
}
25+
head, prev = head.Next, prev.Next
26+
}
27+
return true
28+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package palindrome_linked_list
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type caseType struct {
10+
input []int
11+
expected bool
12+
}
13+
14+
func TestIsPalindrome(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
input: []int{1, 2},
18+
expected: false,
19+
},
20+
{
21+
input: []int{1, 2, 1},
22+
expected: true,
23+
},
24+
{
25+
input: []int{1, 2, 2, 1},
26+
expected: true,
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := isPalindrome(SliceInt2ListNode(tc.input))
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /