zoukankan      html  css  js  c++  java
  • 【leetcode】【单链表】【61】Merge k Sorted Lists

    #include<iostream>
    using namespace std;
    
    struct ListNode {
    	int val;
    	ListNode *next;
    	ListNode(int x) : val(x), next(NULL) {}
    };
    
    class Solution {
    public:
    	ListNode* rotateRight(ListNode* head, int k) {
    		if (head == NULL||head->next == NULL)
    			return head;
    
    		int numOfNodes=0;
    		ListNode* cur = head;
    		ListNode* last = head;
    		while (cur){//找出链表长度
    			++numOfNodes;
    			last = cur;
    			cur = cur->next;
    		}
    		k = k%numOfNodes;
    		if (k == 0) //注意,开始没有考虑到,要右旋转长度为0
    			return head;
    
    		ListNode* preCur = head;
    		cur = head;
    		k = numOfNodes - k;
    		while (k--){
    			preCur = cur;
    			cur = cur->next;
    		}
    		preCur->next = NULL;
    		last->next = head;
    		head = cur;
    		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.rotateRight(head, 0);
    	lst.printNode(head);
    
    	system("pause");
    	return 0;
    }

  • 相关阅读:
    设计模式笔记4(工厂模式)
    设计模式笔记4(工厂模式)
    以前写的东东,放在这里个索引吧
    sicily 1001. Black Magic
    沙漠之旅
    hdu 1395(2^x mod n = 1)
    hdu 2161(Primes)
    sicily 8058. Matrix
    十进制转换为二进制
    硬币水题II
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4558308.html
Copyright © 2011-2022 走看看