LeetCode 61. 旋轉連結串列(C、C++、python)
阿新 • • 發佈:2018-12-16
給定一個連結串列,旋轉連結串列,將連結串列每個節點向右移動 k 個位置,其中 k 是非負數。
示例 1:
輸入: 1->2->3->4->5->NULL, k = 2 輸出: 4->5->1->2->3->NULL 解釋: 向右旋轉 1 步: 5->1->2->3->4->NULL 向右旋轉 2 步: 4->5->1->2->3->NULL
示例 2:
輸入: 0->1->2->NULL, k = 4 輸出:2->0->1->NULL
解釋: 向右旋轉 1 步: 2->0->1->NULL 向右旋轉 2 步: 1->2->0->NULL 向右旋轉 3 步:0->1->2->NULL
向右旋轉 4 步:2->0->1->NULL
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* rotateRight(struct ListNode* head, int k) { if(NULL==head || NULL==head->next) { return head; } struct ListNode* last=head; int count=1; while(last->next) { count++; last=last->next; } k%=count; if(0==k) { return head; } int i=1; struct ListNode* tmp=head; while(i<count-k) { tmp=tmp->next; i++; } struct ListNode* start=tmp->next; tmp->next=NULL; last->next=head; return start; }
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(NULL==head || NULL==head->next) { return head; } int count=1; ListNode* last=head; while(last->next) { count++; last=last->next; } k%=count; if(0==k) { return head; } ListNode* tmp=head; int i=1; while(i<count-k) { tmp=tmp->next; i++; } ListNode* start=tmp->next; tmp->next=NULL; last->next=head; return start; } };
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if None==head or None==head.next:
return head
count=1
last=head
while last.next:
last=last.next
count+=1
k%=count
if 0==k:
return head
tmp=head
i=1
while i<count-k:
tmp=tmp.next
i+=1
start=tmp.next
tmp.next=None
last.next=head
return start