您好,登錄后才能下訂單哦!
這篇文章主要介紹“Python怎么反轉(zhuǎn)單鏈表”,在日常操作中,相信很多人在Python怎么反轉(zhuǎn)單鏈表問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Python怎么反轉(zhuǎn)單鏈表”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
題目:反轉(zhuǎn)單鏈表,可以使用迭代或者遞歸的方法。
迭代的方法,簡(jiǎn)單說下就是:當(dāng)?shù)阶钌顚樱祷氐臅r(shí)候cur的地址和new_head的地址是一致的。操作cur就相當(dāng)于操作new_head。head->next = NULL 就是將已經(jīng)返回后的值丟掉。
Language:C
iteratively :
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* reverseList(struct ListNode* head) {struct ListNode* pre = (struct ListNode *)malloc(sizeof(struct ListNode));struct ListNode* cur = (struct ListNode *)malloc(sizeof(struct ListNode));struct ListNode* temp = (struct ListNode *)malloc(sizeof(struct ListNode));if(head == NULL || head->next == NULL){return head; } pre = head; cur = head->next; pre->next = NULL;while(cur != NULL){ temp = cur->next; cur->next = pre; pre = cur; cur = temp; }return pre; }
recursively:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* reverseList(struct ListNode* head) {struct ListNode* cur = (struct ListNode *)malloc(sizeof(struct ListNode));struct ListNode* new_head = (struct ListNode *)malloc(sizeof(struct ListNode));if(head == NULL || head->next == NULL){return head; }//迭代到最深層,返回的時(shí)候cur的地址和new_head的地址是一致的。操作cur就相當(dāng)于操作new_head。head->next = NULL 就是將已經(jīng)返回后的值丟掉。cur = head->next; new_head = reverseList(cur); head->next = NULL; cur->next = head;return new_head; }
Language : python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object):def reverseList(self, head):""" :type head: ListNode :rtype: ListNode """pre = Nonewhile head: cur = head head = head.next cur.next = pre pre = curreturn pre
到此,關(guān)于“Python怎么反轉(zhuǎn)單鏈表”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。