LeetCode OJ——Rotate List
2015-12-07 12:27
281 查看
题目:
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代表的是链表下标,然后发现多次提交之后,给出的例子貌似有冲突。于是百度了一下该题正确的意思,发现是旋转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
代码:
class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == NULL || head->next == NULL || k == 0) { return head; } else{ ListNode *p = head; //用来遍历的指针 ListNode *tail = NULL; //尾节点 ListNode *newhead = NULL; //新的头指针 ListNode *newtail = NULL; //新的尾节点 int len = 0; //链表长度 //第一步计算链表的长度 while (p->next != NULL) { len++; p = p->next; } tail = p; len++; //第二部,计算需要翻转的节点数num,同时进行翻转 int num = k % len; if (num == 0 || num == len) { return head; } else { newtail = head; int count = 1; while (count < (len - num )) { newtail = newtail->next; count++; } newhead = newtail->next; tail->next = head; newtail->next = NULL; return newhead; } } } };
结果:
思路:
刚开始把题目意思理解错了,以为k代表的是链表下标,然后发现多次提交之后,给出的例子貌似有冲突。于是百度了一下该题正确的意思,发现是旋转k的节点。然后思路就很清晰了
相关文章推荐
- 关于 GET 和 POST 请求的简单示例
- iOS基础-选择空间Picker View的简单使用
- 国外对华反倾销与“非市场经济”问题的思考及应对
- CMake使用总结
- Git分支的创建与合并
- Android帧动画
- Delphi异常处理机制
- code manager toos TotoiseSVN解锁
- 我国外汇储备适度规模的动态研究
- PHP中Enum(枚举)用法实例详解
- 在OpenStack里如何用Ironic管理IBM Power8裸机
- 我国外汇储备适度规模再思考
- php数据转换,数据的实质总是十进制的。字符串
- 2015年科技巨头的十个开源产品,不只是.NET、Swift
- .Net下一个类型转换神器
- 关于我国外汇储备适度规模的分析思考
- Dynamics CRM Trace Reader for Microsoft Dynamics CRM
- 【2015ZUFE新生赛网络同步赛M】【DP 打表 二分】GW I (3) 暴力预处理+分类打表二分查找
- vsphere vmware 装系统
- js正则表达式