[LeetCode] Rotate List
来源:互联网 发布:看三维彩超数据分男女 编辑:程序博客网 时间:2024/06/15 14:09
Rotate List 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.
题目的意思先梳理下,如果list的长度是sz那么k需要模sz k = k%sz;
这里正向处理会比较方便,以题目为例,k=2时,需要从前往后找到第sz-k=3个节点作为新的tail。新的头节点是tail->next。拼接的话是将原来的尾节点接到原来的头结点上。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: int List_size(ListNode* head){ int sz= 0; while(head){ ++sz; head = head->next; } return sz; } ListNode* rotateRight(ListNode* head, int k) { if(k==0||head ==NULL||head->next==NULL) return head; ListNode *phead = head; ListNode *ptail = head; int h_sz = List_size(phead); phead = head; if(k%h_sz==0) return head; k = h_sz-k%h_sz; while(--k) ptail = ptail->next; phead = ptail->next; ptail->next = NULL; ptail = phead; while(ptail->next) ptail = ptail->next; ptail->next = head; return phead; }};
需要注意的是一些退化的情况
1)输入为[]时都要直接返回head
2)输入k=0时说明不旋转,直接返回head
3) 如果list只有一个元素,无论k等于多少,都要返回head
这三个对应于 if(k==0||head ==NULL||head->next==NULL) return head;
4)k%h_sz==0说明旋转的长度是链表长度的整数倍,直接放回head.
8ms AC
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
- Android之WebView和js交互-调用失败的看这里
- 什么是ODBC
- HDU 2141 Can you find it? (二分查找)
- Java数组拷贝
- ios原生地图开发篇
- [LeetCode] Rotate List
- c++ 堆和栈的简析
- Android 开源项目分类汇总
- 黑马程序员--Objective-C 中类的理解
- 切换默认临时表空间
- 图论05—Dijkstra算法(经典)
- org.hibernate.LazyInitializationException: failed to lazily initialize a collection..的解决方案
- hihoCoder#1015 KMP算法
- Android插件化开发之解决OpenAtlas组件在宿主的注册问题