86. Partition List

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.

【思路】两个指针,分别将》=x和《x的节点串起来,再将两个链连接。

/**
 * 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) {
       ListNode* bigH = new ListNode(-1);
       ListNode* smlH = new ListNode(-1);
       ListNode* big = bigH;
       ListNode* sml = smlH;
       if(head==NULL) return head;
       while(head)
       {
           if(head->val < x)
           {
               sml->next = head;
               sml = sml->next;
               head =head->next;
           }else
           {
               big->next= head;
               big = big->next;
               head = head->next;
           }
       }
       big->next = NULL;
       sml->next = bigH->next;
       return smlH->next;
    }
};



你可能感兴趣的:(86. Partition List)