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

被折叠的 条评论
为什么被折叠?



