把链表分成大于,等于,小于某数的区域
做法一:可以将各元素放入数组,通过数组进行分区,最后将数组中的各元素按顺序相连。
做法二:使用节点指针,less,lessEnd,equal,equalEnd,more,moreEnd。遍历链表,将遍历的元素和下一个元素打断,判断该元素是大于,等于还是小于目标值,将元素分发至相应的区域,遍历结束之后将各个区域相连,即可完成分区。
做法二代码:
1 package algorithmTest 2 3 type linkNode struct { 4 next *linkNode 5 val interface{} 6 } 7 8 func (this *linkNode) add(val interface{}) { 9 this.next = new(linkNode) 10 this.next.val = val 11 } 12 13 func partition(node *linkNode, num int) { 14 var less *linkNode 15 var equal *linkNode 16 var more *linkNode 17 var lessEnd *linkNode 18 var equalEnd *linkNode 19 var moreEnd *linkNode 20 for node != nil { 21 //暂存链表下一个元素的地址 22 next := node.next 23 //把链断开,拿一个断一个,最后链表全断了 24 node.next = nil 25 if node.val.(int) == num { 26 if equal == nil { 27 equal = node 28 equalEnd = node 29 } else { 30 equalEnd.next = node 31 equalEnd = node 32 } 33 } 34 if node.val.(int) > num { 35 if more == nil { 36 more = node 37 moreEnd = node 38 } else { 39 moreEnd.next = node 40 moreEnd = node 41 } 42 } 43 if node.val.(int) < num { 44 if less == nil { 45 less = node 46 lessEnd = node 47 } else { 48 lessEnd.next = node 49 lessEnd = node 50 } 51 } 52 node = next 53 } 54 var head *linkNode 55 if less != nil { 56 head = less 57 } else if equal != nil { 58 head = equal 59 } else { 60 head = more 61 } 62 if lessEnd != nil { 63 if equal != nil { 64 lessEnd.next = equal 65 } else { 66 lessEnd.next = more 67 } 68 } 69 if equalEnd != nil { 70 equalEnd.next = more 71 } 72 for ; head != nil; { 73 println(head.val.(int), " ") 74 head = head.next 75 } 76 }
测试代码:
package algorithmTest import ( "testing" "math/rand" ) func Test_partition(t *testing.T) { var node *linkNode var head *linkNode for i := 0; i < 10; i++ { if head == nil { node = new(linkNode) node.val = rand.Intn(50+1) head = node } else { node.add(rand.Intn(50)+1) node = node.next } } partition(head,32) }
结果: