zoukankan      html  css  js  c++  java
  • 【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;
    }

  • 相关阅读:
    【4】通过简化的正则表达式处理字符串
    水晶报表WEB方式下不打印的问题
    字符串处理总结(旧)
    【3】利用Word模板生成文档的总结
    这个教授的观点颇犀利
    互联网时代还需要看书吗?
    怎样更爽地看PDF杂志
    吐槽win7
    信息技术真有想象的那么靠谱吗?
    无线路由器桥接的设置
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4558301.html
Copyright © 2011-2022 走看看