061 Rotate List [Leetcode]
2015-10-27 20:48
260 查看
题目内容:
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.
思路:
使用双指针。注意处理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->NULL and k = 2,
return 4->5->1->2->3->NULL.
思路:
使用双指针。注意处理k比链表长度还要大的情况。
/** * Definition for singly-linked list. * 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) return NULL; ListNode *pre = head, *tail(NULL), *newHead(NULL); int len(1); while(pre->next != NULL) { ++len; pre = pre->next; } k %= len; if(len == 1 || k == 0) return head; tail = pre; pre = head; for(int i = 0; i < len - k - 1; ++i) { pre = pre->next; } newHead = pre->next; pre->next = NULL; tail->next = head; return newHead; } };
相关文章推荐
- Unity界面入门教程
- PostgreSQL学习笔记(一)
- 图的邻接矩阵存储与遍历
- (六)我的JavaScript系列:更好的JavaScript之CoffeeScript
- 图的邻接矩阵建立以及遍历方法
- 【UIKit-98-1】UISlider
- Ubuntu14.04使用QEMU模拟ARM平台开发环境
- 用较小的代价去除字符串中的空格
- 20135304刘世鹏——信息安全系统设计基础第周六学习总结
- STM32把PC13、PC14、PC15、PB3、PB4、PA15作为普通IO使用
- CSS 属性behavior
- Unity脚本入门
- Java:多态性
- android 59 LinearLayout 线性布局
- sqlplus的显示问题
- select函数详解
- Web缓存机制浅析
- 【JavaScript】4、执行环境、变量对象与声明提前
- C++ 命令模式
- 【UUIKit-51-1】UIImageView-创建与属性