Rotate List
来源:互联网 发布:语音识别 python 编辑:程序博客网 时间:2024/06/04 19:19
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
.
求出长度L,将tail指针移到最后一个节点位置,tail的下一个节点为头节点,这样就形成了环。用ptr指针找到L-k-1的位置,即3的位置,将ptr(3)的下一个节点赋值给head,并将NULL赋值给ptr(3)的下一个节点,这样就成功断开了环。
/** * 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; if (k==0)return head; ListNode *ptr=head,*tail=head; int l=0; while(ptr){ tail=ptr; //tail移动到最后一个位置。 ptr=ptr->next; l++; } tail->next=head; //形成环 ptr=head; //回到头节点处 k=k%l; for(int i=0;i<l-k-1;i++)ptr=ptr->next; //找到3 head=ptr->next; //4赋值给头节点 ptr->next=NULL; //3的下一个节点为空 return head; }};
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
- Running a Service in the Foreground
- 学习C/C++中static关键字
- d3,圆弧 arc,饼图
- 返回一个字符串中重复出现的最长字串的长度及其开始字符
- CLOCK_MONOTONIC and CLOCK_REALTIME
- Rotate List
- Win8.1下COCOS2D-X 3.4环境搭建
- C# 中如何编写和调用自己的DLL
- hdu 1348 wall (计算几何,凸包)
- .Net 垃圾回收和大对象处理
- POJ 3134 - Power Calculus (IDDFS)
- iOS笔记-(Block基础知识和使用)
- Bitmap算法
- POJ-1198(BFS)