Rotate List
来源:互联网 发布:防火墙端口 编辑:程序博客网 时间:2024/06/10 12:40
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 个元素 等价 左移 len-k 个元素。(len是list的长度)
几个细节:
1. k>=len时, k = k % len. (0<=k<=len-1)
2. 取模后,k = len-k. (1<=k<=len) 如果 k==len,直接返回head。
处理一般情况:
根据k的大小,将 list 分为长度 len-k 和 k 2个部分,分别记为 L1 和 L2。
然后将 L1 的最后一个节点的 next 设置为 NULL;将 L2 的最后一个节点的 next 设置为原 list 的 head。
最后将L2 的头节点作为旋转后的 list 新头节点返回即可。
ListNode *rotateRight(ListNode *head, int k) { if(NULL==head || NULL==head->next || k<=0){ return head; } int len = 0; ListNode* cur = head; ListNode* tail; while(cur!=NULL){ len = len + 1; if(cur->next == NULL){ tail = cur; } cur = cur->next; } k = k%len; k = len -k; if(k==len){ return head; } ListNode* MiddleNode = head; while(k>1){ MiddleNode = MiddleNode->next; k = k-1; } ListNode* NewHead = MiddleNode->next; MiddleNode->next = NULL; tail->next = head; return NewHead; }
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- GDI+实现的图片相互转换程序,可以通过命令行参数来调用
- Word Break
- apache tika技术了解
- jquery读取xml文件实现省市县三级联动
- Qt版的Rtsp客户端
- Rotate List
- Qt模块化笔记之network——第二个TCP程序,传输图片文件的实现(2)
- 中科大地图导航
- eclipse报错
- ZJUT1296
- Java数据连接池
- 函数调用过程-栈帧 和 进程的关系
- hdu1261 JAVA
- EM算法主观理解