Python怎么反转单链表

发布时间:2021-12-18 15:51:34 作者:iii
来源:亿速云 阅读:126

这篇文章主要介绍“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怎么反转单链表”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. 什么是Python?Python为什么这么抢手?
  2. python教程 - 猿说python

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Python怎么将链表旋转到右侧

下一篇:如何进行springboot配置templates直接访问的实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》