LeetCode Partition List

链接: https://oj.leetcode.com/problems/partition-list/


双重指针......

/**
 * 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 **t1,**t2;
			ListNode *ans1=NULL,*ans2=NULL;
			bool s1,s2;
			if(head==NULL)
				return ans1;
			for(s1=true,s2=true;head!=NULL;head=head->next)
			{
				ListNode *t=NULL;
				if(head->val<x)
				{
					
					if(s1)
					{
					    t=new ListNode(head->val);
					    t1=&t;
						ans1=t;
						s1=false;
					}
					else
					{
					    *t1=new ListNode(head->val);
					}
					t1=&((*t1)->next);
				}
				else
				{
					
					if(s2)
					{
					    t=new ListNode(head->val);
					    t2=&t;
						ans2=t;
						s2=false;
					}
					else
					{
					    *t2=new ListNode(head->val);
					}
					t2=&((*t2)->next);

				}
			}
			if(s1)
				return ans2;
			if(s2)
				return ans1;
			*t1=ans2;
			return ans1;
		}
};



原文地址:https://www.cnblogs.com/frankM/p/4399457.html