这篇文章主要介绍“Python怎么反转单链表”,在日常操作中,相信很多人在Python怎么反转单链表问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python怎么反转单链表”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
题目:反转单链表,可以使用迭代或者递归的方法。
迭代的方法,简单说下就是:当迭代到最深层,返回的时候cur的地址和new_head的地址是一致的。操作cur就相当于操作new_head。head->next = NULL 就是将已经返回后的值丢掉。
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; }//迭代到最深层,返回的时候cur的地址和new_head的地址是一致的。操作cur就相当于操作new_head。head->next = NULL 就是将已经返回后的值丢掉。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
到此,关于“Python怎么反转单链表”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/220256.html