Pārlūkot izejas kodu

add 'Partition List'

tangs 5 gadi atpakaļ
vecāks
revīzija
76017c6d8c
1 mainītis faili ar 91 papildinājumiem un 0 dzēšanām
  1. 91 0
      tags/linked-list/partitionList/main.go

+ 91 - 0
tags/linked-list/partitionList/main.go

@@ -0,0 +1,91 @@
+package main
+
+import "fmt"
+
+func main() {
+	var vals []int
+	var x int
+
+	vals = []int{}
+	x = 3
+	printList(partition(createList(vals), x))
+
+	vals = []int{1}
+	x = 3
+	printList(partition(createList(vals), x))
+
+	vals = []int{1, 2}
+	x = 3
+	printList(partition(createList(vals), x))
+
+	vals = []int{1, 3}
+	x = 3
+	printList(partition(createList(vals), x))
+
+	vals = []int{3, 1, 2}
+	x = 3
+	printList(partition(createList(vals), x))
+
+	vals = []int{1, 4, 3, 2, 5, 2}
+	x = 3
+	printList(partition(createList(vals), x))
+}
+
+//Definition for singly-linked list.
+type ListNode struct {
+	Val  int
+	Next *ListNode
+}
+
+func createList(vals []int) *ListNode {
+	var head, list *ListNode
+	for _, v := range vals {
+		if head == nil {
+			list = &ListNode{Val: v, Next: nil}
+			head = list
+			continue
+		}
+		var temp = &ListNode{Val: v, Next: nil}
+		list.Next = temp
+		list = list.Next
+	}
+	return head
+}
+
+func printList(node *ListNode) {
+	var temp = node
+	for temp != nil {
+		fmt.Printf("%d", temp.Val)
+		if temp.Next != nil {
+			fmt.Printf("%s", "->")
+		}
+		temp = temp.Next
+	}
+	fmt.Println()
+}
+
+func partition(head *ListNode, x int) *ListNode {
+	var left, right = &ListNode{}, &ListNode{}
+	var leftCursor, rightCursor = left, right
+	var temp = head
+	for temp != nil {
+		if temp.Val < x {
+			var node = &ListNode{
+				Val:  temp.Val,
+				Next: nil,
+			}
+			leftCursor.Next = node
+			leftCursor = leftCursor.Next
+		} else {
+			var node = &ListNode{
+				Val:  temp.Val,
+				Next: nil,
+			}
+			rightCursor.Next = node
+			rightCursor = rightCursor.Next
+		}
+		temp = temp.Next
+	}
+	leftCursor.Next = right.Next
+	return left.Next
+}