Partition List Solutions in Go
Number 86
Difficulty Medium
Acceptance 41.7%
Link LeetCode
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport ("github.com/halfrost/LeetCode-Go/structures")// ListNode definetype ListNode = structures.ListNode/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/// 解法一 单链表func partition(head *ListNode, x int) *ListNode {beforeHead := &ListNode{Val: 0, Next: nil}before := beforeHeadafterHead := &ListNode{Val: 0, Next: nil}after := afterHeadfor head != nil {if head.Val < x {before.Next = headbefore = before.Next} else {after.Next = headafter = after.Next}head = head.Next}after.Next = nilbefore.Next = afterHead.Nextreturn beforeHead.Next}// DoublyListNode definetype DoublyListNode struct {Val intPrev *DoublyListNodeNext *DoublyListNode}// 解法二 双链表func partition1(head *ListNode, x int) *ListNode {if head == nil || head.Next == nil {return head}DLNHead := genDoublyListNode(head)cur := DLNHeadfor cur != nil {if cur.Val < x {tmp := &DoublyListNode{Val: cur.Val, Prev: nil, Next: nil}compareNode := curfor compareNode.Prev != nil {if compareNode.Val >= x && compareNode.Prev.Val < x {break}compareNode = compareNode.Prev}if compareNode == DLNHead {if compareNode.Val < x {cur = cur.Nextcontinue} else {tmp.Next = DLNHeadDLNHead.Prev = tmpDLNHead = tmp}} else {tmp.Next = compareNodetmp.Prev = compareNode.PrevcompareNode.Prev.Next = tmpcompareNode.Prev = tmp}deleteNode := curif cur.Prev != nil {deleteNode.Prev.Next = deleteNode.Next}if cur.Next != nil {deleteNode.Next.Prev = deleteNode.Prev}}cur = cur.Next}return genListNode(DLNHead)}func genDoublyListNode(head *ListNode) *DoublyListNode {cur := head.NextDLNHead := &DoublyListNode{Val: head.Val, Prev: nil, Next: nil}curDLN := DLNHeadfor cur != nil {tmp := &DoublyListNode{Val: cur.Val, Prev: curDLN, Next: nil}curDLN.Next = tmpcurDLN = tmpcur = cur.Next}return DLNHead}func genListNode(head *DoublyListNode) *ListNode {cur := head.NextLNHead := &ListNode{Val: head.Val, Next: nil}curLN := LNHeadfor cur != nil {tmp := &ListNode{Val: cur.Val, Next: nil}curLN.Next = tmpcurLN = tmpcur = cur.Next}return LNHead}