leetcode--Rotate List
2014-11-12 14:01
155 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
为了方便,使用了哨兵节点。
java:
c++:
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
为了方便,使用了哨兵节点。
java:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head==null||head.next==null||n==0) return head; int cnt=0; ListNode p=head; while(p!=null){ cnt++; p=p.next; } if(n==cnt) return head; n=n%cnt; if(0==n) return head; ListNode h = new ListNode(-1); h.next=head; ListNode q=h; int step=0; while(step<n){ step++; q=q.next; } p=h; while(q.next!=null){ q=q.next; p=p.next; } q.next=h.next; h.next=p.next; p.next=null; return h.next; } }
c++:
/** * 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||!head->next||0==k){ return head; } ListNode *p=head; int N=0; while(p){ N++; p=p->next; } if(k==N) return head; k=k%N; if(k==0) return head; ListNode *h = (ListNode *)malloc(sizeof(ListNode)); h->next=head; ListNode*q=h; int cnt=0; while(cnt<k){ cnt++; q=q->next; } p=h; while(q->next){ q=q->next; p=p->next; } q->next=h->next; h->next=p->next; p->next=NULL; ListNode *s =h->next; free(h); return s; } };
相关文章推荐
- 【Leetcode】Rotate List
- leetcode 61:Rotate List
- (Java)LeetCode-61. Rotate List
- Leetcode -- Rotate List
- leetcode-61. Rotate List
- leetcode 61.Rotate List
- [leetcode]Rotate List
- Leetcode-Rotate List
- LeetCode 61. Rotate List
- LeetCode-Rotate List
- 【Leetcode】【Medium】Rotate List
- LeetCode----- 61. Rotate List
- LeetCode_Rotate List
- leetcode 61. Rotate List
- [leetcode] Rotate List
- LeetCode: Rotate List
- 【leetcode每日一题】61.Rotate List
- [Leetcode] Rotate List
- leetcode--Rotate List
- Leetcode 61. Rotate List