划分链表后连接链表 leedcode166

#include

struct ListNode{
	int val;
	ListNode* next;
	ListNode(int x) : val(x),next(NULL){}
};

class Solution{
	public:
		ListNode* partition(ListNode* head,int x){
			ListNode less_head(0);				//设置两个临时的结点 
			ListNode more_head(0);
			ListNode *less_ptr = &less_head;	//对应指针指向这两个结点 
			ListNode *more_ptr = &more_head;
			while(head){
				if(head->val < x){				//如果结点值小于x,则将改结点插入less_ptr后 
					less_ptr->next = head;
					less_ptr = head;		//连接完后,less_ptr向后移动 
				}
				else{							//否则将改结点插入more_ptr后 
					more_ptr->next = head;
					more_ptr = head;
				}
				head = head->next;				//遍历链表 
			}
			less_ptr->next = more_head.next;	//将less链表尾,与more链表头相连 
			more_ptr->next = NULL;				//将more_ptr即链表尾节点next置为空 
			return less_head.next; 				//less_head的next结点即为新链表头结点,返回 
		}
}; 

int main(){
	ListNode a(1);
	ListNode b(4);
	ListNode c(3);
	ListNode d(2);
	ListNode e(5);
	ListNode f(2);
	a.next = &b;
	b.next = &c;
	c.next = &d;
	d.next = &e;
	e.next = &f;
	Solution slove;
	ListNode *head = slove.partition(&a,3);
	while(head){
		printf("%d\n",head->val);
		head = head->next; 
	} 
	return 0;
}

你可能感兴趣的:(leedcode,链表,数据结构,算法)