• 【leetcode】【单链表】【21】Merge Two Sorted Lists


    #include<iostream>
    using namespace std;
    
    struct ListNode {
    	int val;
    	ListNode *next;
    	ListNode(int x) : val(x), next(NULL) {}
    };
    
    class Solution {
    public:
    	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    		if (l1 == NULL){ //l1空
    			return l2;
    		}else if (l2 == NULL){ //l2空
    			return l1;
    		}else{ //都不空
    			ListNode* cur1 = l1;
    			ListNode* cur2 = l2;
    			ListNode* preCur1 = NULL;
    			if (cur1->val > cur2->val){
    				ListNode* temp = cur2;
    				cur2 = cur2->next;
    				temp->next = cur1;
    				l1 = preCur1 = temp;
    			}else{
    				preCur1 = cur1;
    				cur1 = cur1->next;
    			}
    			while (cur1&&cur2){
    				if (cur1->val > cur2->val){
    					ListNode* temp = cur2;
    					cur2 = cur2->next;
    					temp->next = cur1;
    					preCur1->next = temp;
    					preCur1 = temp;
    				}else{
    					preCur1 = cur1;
    					cur1 = cur1->next;
    				}
    			}
    			if (cur2)
    				preCur1->next = cur2;
    			return l1;
    		}	
    	}
    	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(){
    	Solution solution;
    
    	ListNode* l1 = NULL;
    	l1 = solution.createList(l1);
    	solution.printNode(l1);
    
    	ListNode* l2 = NULL;
    	l2 = solution.createList(l2);
    	solution.printNode(l2);
    
    	l1 = solution.mergeTwoLists(l1, l2);
    	solution.printNode(l1);
    
    	system("pause");
    	return 0;
    }

  • 相关阅读:
    c中NULL,'\0'和0之间的区别. (the difference between NULL,'\0' and 0 in c)
    python 解析xml文件python parse xml.
    mysql升级 ,MySQL Error: #1558 Column count of mysql.proc is wrong. Expected 20, found 16.
    文献随笔15
    文献笔记11
    文献笔记16
    文献笔记13
    文献笔记17
    文献笔记20
    文献笔记19
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4558312.html
Copyright © 2020-2023  润新知