Sharing my C# solution on pass, easy to understand


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode Partition(ListNode head, int x) {
            
            //create two new nodelist for larger and smaller nodes
            ListNode smallHead = new ListNode(0);
            ListNode bigHead = new ListNode(0);
            var tempSmallHead=smallHead;
            var tempBigHead=bigHead;
            
            var curr=head;
            while(curr!=null)
            {
                var nextTemp = curr.next;
                curr.next = null;
                if(curr.val < x)
                {
                    smallHead.next = curr;
                    smallHead = smallHead.next;
                }
                else
                {
                    bigHead.next = curr;
                    bigHead = bigHead.next;
                }
                
                curr = nextTemp;
            }
            
            smallHead.next = tempBigHead.next;
            
            
            return tempSmallHead.next;
            
        }
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.