LeetCode探索之旅(60)-206反转链表
2019-03-22 09:51
447 查看
今天继续刷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。
相关文章推荐
- leetcode206/92---Reverse Linked List I/II(反转链表)
- leetcode206 Reverse Linked List(反转链表)
- leetcode206 反转链表
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- 编程集训第2天:LeetCode--环形链表2(142)及单链表反转(206)C++和python代码实现
- Leetcode 206 反转链表 Java
- [LeetCode-206] Reverse Linked List(链表反转)
- C#LeetCode刷题之#206-反转链表(Reverse Linked List)
- 206. 反转链表 [Leetcode] 206. 反转链表 java 迭代和递归
- LeetCode206——Reverse Linked List 反转链表
- scala反转链表 leetcode 206 Reverse Linked List
- LeetCode 206 Reverse Linked List(反转链表)(四步将递归改写成迭代)(*)
- leetcode206-Reverse Linked List-反转链表
- LeetCode206: 反转链表
- leetcode解题之206 # Reverse Linked List Java版 (使用头插法反转链表)
- LeetCode206反转链表
- LeetCode 206 Reverse Linked List(反转链表)(Linked List)(四步将递归改写成迭代)(*)
- leetCode_反转链表那些事儿
- LeetCode 206 Reverse Linked List(链表操作)
- LeetCode-探索-初级-字符串-反转字符串-java