LeetCode | Rotate List(循环右移链表)
2014-08-18 15:16
316 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
题目解析:
题目很好理解,但是当k>n的时候k = k%n。然后再进行,也就是要先遍历一边链表求出其长度。
有了链表以后,也不能直接找到n-k-1的结点,因为链表最后的指针还要指向头结点。但网友有个办法,遍历链表时只遍历到最后一个结点然后计算总长度。
先上自己的代码:
再看网友的代码:
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
题目解析:
题目很好理解,但是当k>n的时候k = k%n。然后再进行,也就是要先遍历一边链表求出其长度。
有了链表以后,也不能直接找到n-k-1的结点,因为链表最后的指针还要指向头结点。但网友有个办法,遍历链表时只遍历到最后一个结点然后计算总长度。
先上自己的代码:
class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || k <= 0) return head; int n = 0; ListNode *p = head; while(p){ p = p->next; ++n; } if(k%n == 0) return head; k = k%n; //循环找 p = head; int i = 1; //找到第k个节点 while(p->next && i < k){ p = p->next; i++; } //这时候p一定不为NULL,因为k<n ListNode *q = head; p = p->next; while(p->next != NULL){ p = p->next; q = q->next; //p遍历完以后,指向倒数第K+1个结点 } p->next = head; head = q->next; q->next = NULL; return head; } };
再看网友的代码:
class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head==NULL)return NULL; ListNode *p=head; int n=0; while(p->next) { p=p->next; n++; } n++; k=k%n; p->next=head; //这里就处理了尾指针 ListNode *q=head; for(int i=0;i<n-k-1;i++) q=q->next; head=q->next; q->next=NULL; return head; } };
相关文章推荐
- LeetCode-----61. Rotate List(循环旋转链表)
- LeetCode 61. Rotate List 链表的右循环
- leetcode 61 --Rotate List 链表 循环/断开 翻转
- LeetCode:Rotate List(旋转链表)
- C实现 LeetCode->Rotate List(双指针大法)(单链表 部分旋转)
- LeetCode-61-Rotate List 链表水题
- leetcode Rotate list (链表旋转)的python实现
- Leetcode解题-链表(2.2.6)RotateList
- [leetcode] 【链表】 61. Rotate List
- Leetcode 61. Rotate List (旋转链表)
- leetcode---Rotate List---链表
- leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- LeetCode中几道链表反转相关题目(Reorder List、Rotate List、Reverse Nodes in k-Group)
- Leetcode Rotate List 旋转链表
- LeetCode Rotate List (链表操作)
- Leetcode #61. Rotate List 循环位移链表 解题报告
- [Leetcode] Rotate list 旋转链表
- leetcode解题61. Rotate List java版(旋转链表)