Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

86. 分隔链表 #3

Open
yankewei opened this issue Feb 27, 2020 · 0 comments
Open

86. 分隔链表 #3

yankewei opened this issue Feb 27, 2020 · 0 comments
Labels
中等 题目难度为中等 双指针 题目包含双指针解法 链表 题目类型为链表

Comments

@yankewei
Copy link
Owner

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func partition(head *ListNode, x int) *ListNode {
    beforeTmp := &ListNode{}
    afterTmp := &ListNode{}
    before := beforeTmp
    after := afterTmp

    for head != nil {
        if head.Val < x {
            beforeTmp.Next = head
            beforeTmp = beforeTmp.Next 
        } else {
            afterTmp.Next = head
            afterTmp = afterTmp.Next
        }
        head = head.Next
    }
    afterTmp.Next = nil
    beforeTmp.Next = after.Next
    return before.Next
}
@yankewei yankewei added 中等 题目难度为中等 链表 题目类型为链表 双指针 题目包含双指针解法 labels Feb 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 双指针 题目包含双指针解法 链表 题目类型为链表
Projects
None yet
Development

No branches or pull requests

1 participant