Rotate List ,反转链表的右k个元素
2016-08-09 15:32
330 查看
问题描述:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
算法分析:这个k是可以超过链表长度的,所以要对k取模。
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
算法分析:这个k是可以超过链表长度的,所以要对k取模。
public ListNode rotateRight(ListNode head, int k) { int lenth = 0;//链表长度 ListNode headd = head; while (headd != null) { lenth++; headd = headd.next; } if (head == null || head.next == null || k % lenth == 0) { return head; } ListNode headc = head; for (int i = 1; i < lenth - k % lenth; i++) { headc = headc.next; } ListNode newHead = headc.next; ListNode p = newHead; while (p.next != null) { p = p.next; } p.next = head; headc.next = null; return newHead; }
相关文章推荐
- 【链表】反转/逆置 链表,以及升级版Node* RotateList(Node* list, size_t k)
- LeetCode中几道链表反转相关题目(Reorder List、Rotate List、Reverse Nodes in k-Group)
- leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
- 输入一个链表,反转链表后,输出链表的所有元素。
- STL链表之删除指定元素(list)
- 链表的反转问题(Reverse Linked List)
- Remove Duplicates from Sorted List ,除去链表中相邻的重复元素
- 输入一个链表,反转链表后,输出链表的所有元素。就地逆转,头插法
- 反转链表后,输出链表的所有元素。
- 输入一个链表,反转链表后,输出链表的所有元素。
- 带有首尾的可反转链表(LinkedList)的java实现
- leetcode:Remove Duplicates from Sorted List(去除链表中重复元素)【面试算法题】
- leetcode之92. Reverse Linked List II(C++读错题版本,交换一个链表中指定的两个位置上的元素)
- 92. Reverse Linked List II【遍历一遍就反转链表】
- 112. 删除排序链表中的重复元素(remove-duplicates-from-sorted-list)(c++)----lintcode面试题之链表
- leetcode解题之206 # Reverse Linked List Java版 (使用头插法反转链表)
- [LeetCode] Reverse Linked List(递归与非递归反转链表)
- Rotate List (列表旋转k个元素)
- Remove Duplicates from Sorted List --已出有序链表中的重复元素
- 1.1数组和链表:61. Rotate List(Leetocde)