leetcode 118: Partition List

来源:互联网 发布:网络机房建设国家标准 编辑:程序博客网 时间:2024/04/30 14:26

Partition ListApr 30 '12

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.



/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */ //null, {}, {1}x=1, {1,2,3,4} x=3 public class Solution {    public ListNode partition(ListNode head, int x) {        // Start typing your Java solution below        // DO NOT write main() function        if(head==null) return null;                ListNode low = new ListNode(0);        ListNode p = low;        ListNode high = new ListNode(0);        ListNode q = high;        while(head!=null) {            int y = head.val;            if(y<x) {                p.next = head;                p = p.next;            } else {                q.next = head;                q = q.next;            }            head = head.next;        }        p.next = high.next;        q.next = null;        return low.next;    }}


this approach won't reserve the order of original list, but in-place

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *partition(ListNode *head, int x) {        // Start typing your C/C++ solution below        // DO NOT write int main() function         //1 2 5 3 2 4         ListNode *i=head, *j = head;                  while(j!=nullptr) {             if(j->val<x) {                 swap(i->val, j->val);                 i = i->next;             }                          j = j->next;         }                  return head;    }};



 

原创粉丝点击