您好,登錄后才能下訂單哦!
本篇內容介紹了“Python怎么將鏈表旋轉到右側”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
For example:
Given
1->2->3->4->5->NULL and k = 2
return
4->5->1->2->3->NULL
題目: 給定一個鏈表,通過k(非負)節點將鏈表旋轉到右側。
解讀: 一直感覺這個題目的表述有些問題。我是這樣理解才做對題的:保留后k個節點,比如example給出的k=2,那么保留4->5,前面的3個節點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等于鏈表長度,不旋轉return head; } k = listlength - k; //移動前面listlength-k個節點到右側,后k個節點不動tail->next = head; //尾節點連接首節點for(index; index < k-1; index++){ //找都新鏈表頭newlist = newlist->next; } head = newlist->next; //新鏈表頭newlist->next = NULL; //鏈表結尾賦值NULLreturn head; //返回鏈表頭結點}
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等于鏈表長度,不旋轉return head; } k = listlength - k; //移動前面listlength-k個節點到右側,后k個節點不動tail->next = head; //尾節點連接首節點ListNode *newlist = head;for(int index = 0; index < k-1; index++){ //找都新鏈表頭newlist = newlist->next; } head = newlist->next; //新鏈表頭newlist->next = NULL; //鏈表結尾賦值NULLreturn head; //返回鏈表頭結點} };
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怎么將鏈表旋轉到右側”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。