LeetCode探索之旅(60)-206反转链表

博客记录了刷LeetCode第206题反转链表的过程。题目要求用递归和迭代实现,采用头插法,设置三个指针防止断链。分析了头插法逻辑关系,给出C++迭代和递归代码,还有python代码,并指出python使用头结点且初始为0,C++新链表无头结点。

今天继续刷LeetCode,第206题,反转链表

分析:
题目要求用递归以及迭代实现,采用头插法的方式,反转链表。对于头插法,设置三个指针,防止断链,一个直线前一个节点,一个当前节点,一个下一个节点。

问题:
1、注意头插法的逻辑关系;

迭代:
附上C++迭代代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre=NULL;
        ListNode* last=head;
        while(head)
        {
            last=head->next;
            head->next=pre;
            pre=head;
            head=last;
        }
        return pre;
    }
};

递归:
1、递归体;
2、递归出口;

附上C++递归代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL)
            return head;
        ListNode* node=reverseList(head->next);
        head->next->next=head;
        head->next=NULL;
        return node;
    }
};

附上python代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        new_head=ListNode(0)
        if head==None:
            return head
        while head:
            next_p=head.next
            head.next=new_head.next
            new_head.next=head
            head=next_p
        return new_head.next
            

python与C++不同的地方是,C++中新的链表没有头结点,而python中使用了头结点,而且初始为0。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值