classSolution { public ListNode partition(ListNode head, int x) { ListNodesmall=newListNode(0); ListNodesmallHead= small; ListNodelarge=newListNode(0); ListNodelargeHead= large; while (head != null) { if (head.val < x) { small.next = head; small = small.next; } else { large.next = head; large = large.next; } head = head.next; } large.next = null; small.next = largeHead.next; return smallHead.next; } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var partition = function(head, x) { let small = newListNode(0); const smallHead = small; let large = newListNode(0); const largeHead = large; while (head !== null) { if (head.val < x) { small.next = head; small = small.next; } else { large.next = head; large = large.next; } head = head.next; } large.next = null; small.next = largeHead.next; return smallHead.next; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcpartition(head *ListNode, x int) *ListNode { small := &ListNode{} smallHead := small large := &ListNode{} largeHead := large for head != nil { if head.Val < x { small.Next = head small = small.Next } else { large.Next = head large = large.Next } head = head.Next } large.Next = nil small.Next = largeHead.Next return smallHead.Next }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
struct ListNode* partition(struct ListNode* head, int x) { structListNode* small =malloc(sizeof(struct ListNode)); structListNode* smallHead = small; structListNode* large =malloc(sizeof(struct ListNode)); structListNode* largeHead = large; while (head != NULL) { if (head->val < x) { small->next = head; small = small->next; } else { large->next = head; large = large->next; } head = head->next; } large->next = NULL; small->next = largeHead->next; return smallHead->next; }