leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
2017-09-04 16:10
483 查看
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.
这道题考查的是链表旋转,最初我想到了双指针和移动窗口,但是发现没用,网上看了一个做法,就是连接成环,然后查询相关元素,然后拆开环即可。
最方便的方法就是把原有链表连接成为一个环,然后遍历,断开环即可,
代码如下:
下面是C++的做法,就是连成一个环,然后正着查就可以了
代码如下:
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
这道题考查的是链表旋转,最初我想到了双指针和移动窗口,但是发现没用,网上看了一个做法,就是连接成环,然后查询相关元素,然后拆开环即可。
最方便的方法就是把原有链表连接成为一个环,然后遍历,断开环即可,
代码如下:
/*public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } */ /* * 这个应该想到双指针的用法,不过本题用不到 * * 可以考虑吧收尾连接成为一个环,倒数第k个(k>=1),相当于正数(len+1)-k%len个, * 它的父节点是(len+1)-k%len-1个 * 然后做相关操作即可 * */ public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null||k<=0) return head; //得到链表的length,以及最后一个结点 ListNode iter=head; int len=1; while(iter.next!=null) { iter=iter.next; len++; } //连成环 iter.next=head; //正着数的父节点 int n=(len+1)-k%len; for(int i=0;i<n-1;i++) iter=iter.next; //设置head和尾节点 head=iter.next; iter.next=null; return head; } }
下面是C++的做法,就是连成一个环,然后正着查就可以了
代码如下:
#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 || k<=0) return head; int len = 1; ListNode* i = head; while (i->next != NULL) { len++; i = i->next; } i->next = head; int n = (len + 1) - k%len; for (int j = 0; j < n-1; j++) i = i->next; head = i->next; i->next = NULL; return head; } };
相关文章推荐
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- 【LeetCode题解】61_旋转链表(Rotate-List)
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- LeetCode 61. Rotate List(旋转链表)
- [LeetCode] 61. Rotate List 旋转链表
- leetcode解题61. Rotate List java版(旋转链表)
- Leetcode 61. Rotate List (旋转链表)
- LeetCode-----61. Rotate List(循环旋转链表)
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- [leetcode] 【链表】 61. Rotate List
- LeetCode-61-Rotate List 链表水题
- Rotate List (列表旋转k个元素)
- 61. Rotate List (旋转链表)
- leetcode 61 --Rotate List 链表 循环/断开 翻转
- LeetCode(Rotate List) 旋转链表
- [Leetcode] Rotate list 旋转链表
- LeetCode 61. Rotate List 链表的右循环
- LeetCode:Rotate List(旋转链表)
- C实现 LeetCode->Rotate List(双指针大法)(单链表 部分旋转)
- Leetcode Rotate List 旋转链表