leetcode---rotate-list---链表
2017-10-25 18:47
295 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverse(ListNode *head) { if(!head || !head->next) return head; ListNode *nextH = head->next; ListNode *newH = reverse(nextH); nextH->next = head; head->next = NULL; return newH; } ListNode *rotateRight(ListNode *head, int k) { if(!head || k == 0) return head; int n = 0; ListNode *p = head; ListNode *last = head; while(p) { n++; last = p; p = p->next; } k = k % n; if(k == 0) return head; n = n - k; int i = 1; p = head; while(p && i<n) { i++; p = p->next; } ListNode *next = p->next; p->next = NULL; last->next = head; return next; } };
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【061-Rotate List(旋转单链表)】
- LeetCode:Rotate List(旋转链表)
- [LeetCode] 61. Rotate List 旋转链表
- leetcode_c++:链表:Rotate List(061)
- LeetCode 61. Rotate List 链表的右循环
- Leetcode 61. Rotate List (旋转链表)
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- [leetcode] 【链表】 61. Rotate List
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- C实现 LeetCode->Rotate List(双指针大法)(单链表 部分旋转)
- LeetCode刷题笔记(链表):rotate-list
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- LeetCode中几道链表反转相关题目(Reorder List、Rotate List、Reverse Nodes in k-Group)
- LeetCode-----61. Rotate List(循环旋转链表)
- [Leetcode] Rotate list 旋转链表
- LeetCode | Rotate List(循环右移链表)
- leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
- LeetCode Rotate List (链表操作)
- LeetCode-Rotate List-旋转链表-旋转操作和链表
- leetcode解题61. Rotate List java版(旋转链表)