[LeetCode]Rotate List
来源:互联网 发布:java基础实例程电子书 编辑:程序博客网 时间:2024/06/06 03:33
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
这道题是要求将单链表循环右移k次,每次移动一个结点。
考虑到k大于或等于链表的长度n,所以实际效果等同于循环右移k%n次。
- 遍历单链表,计算出其长度n,并保存指向最后一个结点的尾指针tail
- 对k做预处理,k = k % n
- 顺序遍历单链表,定位到第n-k个结点
- 保存第n-k个结点的后继结点p,将tail的next置为head,并将原来的Head置为q,同时将第n-k个结点的next置为NULL。
需要注意的空链表和n==k的情况。
下面贴上代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* getLength(ListNode* head,int& len){ ListNode* p = head; len = 1; while (p&&p->next){ len++; p = p->next; } return p; } ListNode *rotateRight(ListNode *head, int k) { int len; if (head){ ListNode* tail = getLength(head, len); k = k%len; int count = len - k; ListNode* p = head; while (p&&count > 1){ p = p->next; count--; } ListNode* q = p->next; p->next = NULL; if (q){ tail->next = head; head = q; } } return head; }};
0 0
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- LeetCode 61: Rotate List
- leetcode之Rotate List
- POJ 3126 Prime Path(BFS)
- 用指针处理的一道题
- Hibernate - DetachedCriteria 的完整用法
- PTVS的内存分配失败及处理
- 魔方阵
- [LeetCode]Rotate List
- (转)设计模式-----桥接模式(Bridge Pattern)-Java
- 杨辉三角形
- C++异常规范
- C#数组参数
- 堆排序
- shsfhdsndndmndg
- 搜索行为分析
- 快排序--交换