Skip to content

Commit

Permalink
✨86.分隔链表
Browse files Browse the repository at this point in the history
  • Loading branch information
techoc committed Apr 25, 2024
1 parent d90b008 commit afccece
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@
- [7.整数反转](leetcode/medium/7.go)
- [36.有效的数独](leetcode/medium/36.go)
- [73.矩阵置零](leetcode/medium/73.go)
- [86.分隔链表](leetcode/medium/t86/solution.go)
- [93.复原 IP 地址](leetcode/medium/93.go)
- [99.恢复二叉搜索树](leetcode/medium/99.go)
- [105.从前序与中序遍历序列构造二叉树](leetcode/medium/105.go)
Expand Down
47 changes: 47 additions & 0 deletions leetcode/medium/t86/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package t86

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

// 86. 分隔链表
// https://leetcode.cn/problems/partition-list
func partition(head *ListNode, x int) *ListNode {
// 创建两个链表,分别存储小于x和等于x的节点
less := &ListNode{}
more := &ListNode{}
// 创建两个链表的虚拟头节点 方便插入节点
lessHead := less
moreHead := more
// 遍历链表,将节点插入对应的链表
for head != nil {
if head.Val < x {
// 小于 x 的值放入 less 链表
less.Next = head
less = less.Next
head = head.Next
// 断开 head 和 less 的连接
less.Next = nil
} else {
// 大于等于 x 的值放入 more 链表
more.Next = head
more = more.Next
head = head.Next
// 断开 head 和 more 的连接
more.Next = nil
}
}
// 使用初始化的虚拟头节点 将 more 链表连接在 less 链表之后
less.Next = moreHead.Next
// 返回 less 链表虚拟头节点的下一个节点
return lessHead.Next
}

type ListNode struct {
Val int
Next *ListNode
}
81 changes: 81 additions & 0 deletions leetcode/medium/t86/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package t86

import (
"reflect"
"testing"
)

func TestPartition(t *testing.T) {
tests := []struct {
name string
head *ListNode
x int
want *ListNode
}{
{
name: "Case 1",
head: &ListNode{
Val: 1,
Next: &ListNode{
Val: 4,
Next: &ListNode{
Val: 3,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 5,
Next: &ListNode{
Val: 2,
},
},
},
},
},
},
x: 3,
want: &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 4,
Next: &ListNode{
Val: 3,
Next: &ListNode{
Val: 5,
},
},
},
},
},
},
},
{
name: "Case 2",
head: &ListNode{
Val: 2,
Next: &ListNode{
Val: 1,
},
},
x: 2,
want: &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := partition(tt.head, tt.x); !reflect.DeepEqual(got, tt.want) {
//if got := partition(tt.head, tt.x); !equals(got, tt.want) {
t.Errorf("partition() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit afccece

Please sign in to comment.