• 【leetcode】【单链表】【86】Partition List


    #include<iostream>
    using namespace std;
    
    struct ListNode {
    	int val;
    	ListNode *next;
    	ListNode(int x) : val(x), next(NULL) {}
    };
    
    class Solution {
    public:
    	ListNode* partition(ListNode* head, int x) {
    		if (head == NULL || head->next == NULL)
    			return head;
    		ListNode* cur = head;
    		ListNode* last = head;
    		while (cur){//寻找第一个小于x的节点
    			if (cur->val >= x){
    				last = cur;//记录最后一个大于等于x的节点
    				cur = cur->next;
    			}
    			else
    				break;
    		}
    		if (cur == NULL) //所有节点的值都大于等于x
    			return head;
    
    		ListNode* first = head;//插入点的前一点
    		head = cur;//第一个小于x的节点就是头结点
    
    		if (head != first){//说明第一个小于x的节点前面有节点大于等于x
    			last->next = head->next;
    			head->next = first;
    		}
    		first = head;//插入点的前一点
    		cur = last->next;
    		while (cur){ //我用的方法是一个节点一个节点的插入,而没有用小于x的[first,last)内的节点整体插入
    			if (cur->val < x){
    				if (first==last){//前面的节点的值都是小于x
    					first = last = cur;
    					cur = cur->next;
    				}else{ //有节点的值大于等于x
    					last->next = cur->next;
    					cur->next = first->next;
    					first->next = cur;
    					first = cur;
    					cur = last->next;
    				}
    			}else{
    				cur = cur->next;
    				last = last->next;
    			}
    		}
    		return head;
    	}
    	ListNode* createList(ListNode* head){
    		int numOfNode;
    		int value;
    		cout << "please input number of listNode:";
    		cin >> numOfNode;
    		cin >> value;
    		head = new ListNode(value);
    		ListNode* cur = head;
    		for (int i = 1; i < numOfNode; ++i){
    			cin >> value;
    			ListNode* temp = new ListNode(value);
    			cur->next = temp;
    			cur = temp;
    		}
    		return head;
    	}
    	void printNode(ListNode* head){
    		ListNode* cur = head;
    		while (cur){
    			cout << cur->val << " ";
    			cur = cur->next;
    		}
    		cout << endl;
    	}
    };
    
    int main(){
    	ListNode* head = NULL;
    	Solution lst;
    	head = lst.createList(head);
    	lst.printNode(head);
    
    	head = lst.partition(head, 4);
    	lst.printNode(head);
    
    	system("pause");
    	return 0;
    }

  • 相关阅读:
    div定位左右居中
    highcharts绘制3D倾斜的饼图
    Echarts 图表不能渲染问题整理
    RK:系统手势监听
    RK:网络共存、Shell脚本
    泛型
    ArrayList类
    Linux(centos7)安装ClickHouse
    centos安装宝塔命令
    centos下修改hosts文件以及生效命令
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4558301.html
Copyright © 2020-2023  润新知