Algorithm/java tip

86. Partition List

개구리는 개꿀개꿀 2021. 3. 3. 17:39

leetcode.com/problems/partition-list/submissions/

 

Partition List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode less = new ListNode(0);
		ListNode greater = new ListNode(0);
		
		ListNode lessHead = less;
		ListNode greaterHead = greater;
		
		ListNode cur = head;
		
		while(cur != null) {
			if(cur.val < x) {
				less.next = cur;
				less = less.next;
			} else {
				greater.next = cur;
				greater = greater.next;
			}
			cur = cur.next;
		}
		
		less.next = greaterHead.next;
		greater.next = null;
		return lessHead.next;
    }
}

leetcode.com/problems/partition-list/submissions/