您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Python怎么將鏈表旋轉(zhuǎn)到右側(cè)”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
For example:
Given
1->2->3->4->5->NULL and k = 2
return
4->5->1->2->3->NULL
題目: 給定一個鏈表,通過k(非負(fù))節(jié)點將鏈表旋轉(zhuǎn)到右側(cè)。
解讀: 一直感覺這個題目的表述有些問題。我是這樣理解才做對題的:保留后k個節(jié)點,比如example給出的k=2,那么保留4->5,前面的3個節(jié)點1->2->3右移到后面,形成新鏈表4->5->1->2->3。除此之外,k值也有可能是大于鏈表長度的,需要取余,獲得真實的位移。
Language : c
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* rotateRight(struct ListNode* head, int k) {int index = 0;int listlength = 1;struct ListNode *newlist = (struct ListNode *)malloc(sizeof(struct ListNode));struct ListNode *tail = (struct ListNode *)malloc(sizeof(struct ListNode));if(head == NULL){return NULL; } tail = head; newlist = head;while(tail->next){ //計算鏈表長度tail = tail->next; listlength++; } k = k % listlength; //k可能大于鏈表的長度if(k == 0){ //k等于鏈表長度,不旋轉(zhuǎn)return head; } k = listlength - k; //移動前面listlength-k個節(jié)點到右側(cè),后k個節(jié)點不動tail->next = head; //尾節(jié)點連接首節(jié)點for(index; index < k-1; index++){ //找都新鏈表頭newlist = newlist->next; } head = newlist->next; //新鏈表頭newlist->next = NULL; //鏈表結(jié)尾賦值NULLreturn head; //返回鏈表頭結(jié)點}
Language : cpp
/** * 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; } ListNode *tail = head;int listlength = 1;while(tail->next){ //計算鏈表長度tail = tail->next; listlength++; } k = k % listlength; //k可能大于鏈表的長度if(k == 0){ //k等于鏈表長度,不旋轉(zhuǎn)return head; } k = listlength - k; //移動前面listlength-k個節(jié)點到右側(cè),后k個節(jié)點不動tail->next = head; //尾節(jié)點連接首節(jié)點ListNode *newlist = head;for(int index = 0; index < k-1; index++){ //找都新鏈表頭newlist = newlist->next; } head = newlist->next; //新鏈表頭newlist->next = NULL; //鏈表結(jié)尾賦值NULLreturn head; //返回鏈表頭結(jié)點} };
Language:python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object):def rotateRight(self, head, k):""" :type head: ListNode :type k: int :rtype: ListNode """if not head:return Nonetail = head listlength = 1while tail.next: tail = tail.next listlength += 1k = k % listlengthif k == 0:return head k = listlength - k tail.next = head newlist = headfor each in range(k - 1): newlist = newlist.next head = newlist.next newlist.next = Nonereturn head
“Python怎么將鏈表旋轉(zhuǎn)到右側(cè)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。