LeetCode 61. Rotate List
2017-10-02 22:11
302 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
分析:
旋转链表,新链表的头节点应该是len-k%len的位置,首先计算链表的长度,并且需要一个指针找到尾部节点,因为尾部节点要用来连接头部节点。
然后找到循环移动后的最后一个节点,然后下一个节点的地址就是新节点的头节点,再将后面的节点为null,这里要注意顺序。
最后将尾部节点与头节点链接。
/** * 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||head->next==NULL||k==0) return head; ListNode *l=head,*p=head,*newhead=head,*tail=head; int len=0; while(l!=NULL){ if(l->next==NULL) tail=l;//找到尾部节点,因为尾部节点要连接第一个节点 l=l->next; len++; } k=k%len; if(k==0) return head; for(int i=0;i<len-k-1;i++){ p=p->next; newhead=newhead->next;//找到循环节点的最后一个位置 } newhead=newhead->next;//newhead做为头节点 p->next=NULL; tail->next=head;//尾部节点连接头部节点 return newhead; } };
相关文章推荐
- leetcode 61: Rotate List
- LeetCode 61. Rotate List(旋转链表)
- LeetCode 61. Rotate List
- LeetCode 61: Rotate List
- LeetCode 61. Rotate List
- leetcode 61. Rotate List
- LeetCode_61---Rotate List
- [LeetCode] 61. Rotate List
- leetcode 61 --Rotate List 链表 循环/断开 翻转
- leetcode 61. Rotate List
- LeetCode - 61 - Rotate List
- Leetcode——61. Rotate List
- LeetCode61——Rotate List
- leetcode 61. Rotate List
- LeetCode - 61. Rotate List
- [Leetcode 57] 61 Rotate List
- [leetcode] 61.Rotate List
- leetcode题解-61. Rotate List
- leetcode 61. Rotate List
- 【一天一道LeetCode】#61. Rotate List