leetcode刷题笔记(Golang)--86. Partition List

86. Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func partition(head *ListNode, x int) *ListNode {
	if head == nil {
		return head
	}
	dummy := ListNode{Val: 0}
	greaterDummy := ListNode{Val: 0}
	greaterNode := &greaterDummy
	lessNode := &dummy
	node := head
	for node != nil {
		if node.Val < x {
			lessNode.Next = node
			lessNode = node
		} else {
			greaterNode.Next = node
			greaterNode = node
		}
        //fmt.Println(lessNode.Val,greaterNode.Val)
		node = node.Next
	}
    greaterNode.Next=nil
    lessNode.Next = greaterDummy.Next
    return dummy.Next
}
发布了65 篇原创文章 · 获赞 0 · 访问量 347

猜你喜欢

转载自blog.csdn.net/weixin_44555304/article/details/104320673