【LeetCode】Rotate list
2015-05-12 22:57
148 查看
Question
Method1
Using two pointers to make the distance equal k%ListNode.length()//This is got from a loop/** * 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(k==0) return head; int list_len=0; ListNode *pList=head; for(;pList;pList=pList->next) ++list_len; if(list_len<=1) return head; k=k%list_len; if(k==0) return head; ListNode *pre,*lst; pre=lst=head; int dis=0; while(lst->next){ if(dis!=k){ ++dis; lst=lst->next; }else{ lst=lst->next; pre=pre->next; } } ListNode *tmp=pre->next; pre->next=NULL; lst->next=head; return tmp; } };
Method2
Using a vector<ListNode*>to make find postion of new head easily.
/** * 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) { vector<ListNode*> tmp; int list_len=0; ListNode *pList=head; for(;pList;pList=pList->next) tmp.push_back(pList); list_len=tmp.size(); if(list_len<=1) return head; k=k%list_len; if(k==0) return head; ListNode *resHead=tmp[list_len-k]; tmp[list_len-1]->next=head; tmp[list_len-1-k]->next=NULL; return resHead; } };
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Rotate List
- leetcode--Rotate List
- C++ STL@ list 应用 (leetcode: Rotate Array)
- LeetCode:Rotate List(旋转链表)
- [leetcode]61. Rotate List@Java解题报告
- ( Leetcode 61 ) Rotate List
- [LeetCode] Rotate List
- LEETCODE: Rotate List
- LeetCode Rotate List
- #leetcode#Rotate List
- 【LeetCode-面试算法经典-Java实现】【061-Rotate List(旋转单链表)】
- LeetCode - Rotate List
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- Leetcode 61. Rotate List
- leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
- Leetcode Rotate List
- LeetCode:Rotate List
- Leetcode61 Rotate List
- 【leetcode】Rotate List
- 【leetcode】Rotate List(middle)