LeetCode(Rotate List) 旋转链表
2014-04-17 02:04
381 查看
题目要求:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
思路: 首先求出链表的长度len, k = k % len,然后找到倒数第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.
思路: 首先求出链表的长度len, k = k % len,然后找到倒数第k个节点,添加一个虚拟头结点,然后将倒数第k节点到末尾节点用尾插法插入。
代码:
ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || k <=0) return head; int len = ListLength(head); k = k % len; if(k == 0) return head; ListNode* first = head, *second = head; for(size_t i = 0; i < k; ++i) { first = first->next; } while(first->next != NULL) { first = first->next; second = second->next; } ListNode* rotate_head = second->next; second->next = NULL; ListNode* virtual_head = new ListNode(0); virtual_head->next = head; ListNode* cur = virtual_head; while(rotate_head != NULL) { ListNode* node = rotate_head->next; rotate_head->next = cur->next; cur->next = rotate_head; rotate_head = node; cur = cur->next; } ListNode* ret = virtual_head->next; delete virtual_head; virtual_head = NULL; return ret; } int ListLength(ListNode* head) { if(head == NULL) return 0; int len = 0; while(head != NULL) { ++len; head = head->next; } return len; }
相关文章推荐
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- leetcode解题61. Rotate List java版(旋转链表)
- 【LeetCode-面试算法经典-Java实现】【061-Rotate List(旋转单链表)】
- Leetcode 61. Rotate List (旋转链表)
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- LeetCode-Rotate List-旋转链表-旋转操作和链表
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- [Leetcode] Rotate list 旋转链表
- [LeetCode] 61. Rotate List 旋转链表
- LeetCode-----61. Rotate List(循环旋转链表)
- C实现 LeetCode->Rotate List(双指针大法)(单链表 部分旋转)
- Leetcode Rotate List 旋转链表
- LeetCode 61. Rotate List(旋转链表)
- LeetCode:Rotate List(旋转链表)
- leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
- leetcode Rotate list (链表旋转)的python实现
- 【LeetCode题解】61_旋转链表(Rotate-List)
- 旋转链表---Rotate List
- Leetcode解题-链表(2.2.6)RotateList
- LeetCode刷题笔记(链表):rotate-list