划分链表后连接链表 leedcode166

#include<stdio.h>

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;
}
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试
应支付0元
点击重新获取
扫码支付

支付成功即可阅读