【leetcode】【单链表】【61】Merge k Sorted Lists
2015-05-21 16:43
393 查看
#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; }
相关文章推荐
- 【leetcode】【单链表】【61】Merge k Sorted Lists
- LeetCode刷题笔记(链表):merge-k-sorted-lists
- [LeetCode] Merge k Sorted Lists 合并k个有序链表
- Merge k Sorted Lists 合并k个有序链表@LeetCode
- LeetCode(Merge Two Sorted Lists ) 合并两个有序的链表
- 【LeetCode刷题】排列两个有序链表Merge Two Sorted Lists(递归思想)(java)
- [LeetCode 21]Merge Two Sorted Lists 合并两个有序链表
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python
- leetcode:Merge k Sorted Lists(按大小顺序连接k个链表)【面试算法题】
- leetcode Merge Two Sorted Lists 合并两个有序链表
- LeetCode Merge k Sorted Lists (链表)
- LeetCode 21 Merge Two Sorted Lists (有序两个链表整合)
- 面试题17:合并两个有序链表(Leetcode-21:Merge Two Sorted Lists)
- LeetCode 21. Merge Two Sorted Lists (合并两个有序链表)
- leetcode:Merge Two Sorted Lists (链接两个有序链表)【面试算法题】
- leetcode_c++:链表:Merge Two Sorted Lists(021)
- LeetCodet题解--21. Merge Two Sorted Lists(合并两个排序好的链表)
- 【leetcode】【单链表】【21】Merge Two Sorted Lists
- 【leetcode 链表】 Merge Two Sorted Lists 和 Merge k Sorted Lists
- [LeetCode] Merge Two Sorted Lists 归并两个排好序的单链表