剑指面试题24-反转链表 leetcode 206
2019-03-16 15:54
721 查看
题目:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
分析:需要把头结点的next设置为None,需要保存下一个节点,防止链表断开。
非递归实现:
# -*- coding:utf-8 -*- # class ListNode: # def __init_ 4000 _(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if pHead is None: return pHead last = None #指向上一个节点 while pHead: # 先用tmp保存pHead的下一个节点的信息, # 保证单链表不会因为失去pHead节点的next而就此断裂 tmp = pHead.next # 保存完next,就可以让pHead的next指向last了 pHead.next = last # 让last,pHead依次向后移动一个节点,继续下一次的指针反转 last = pHead pHead = tmp return last
leetcode:
# 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: cur, rev = head, None while cur: rev, rev.next, cur = cur, rev, cur.next return rev
相关文章推荐
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- 【剑指offer】面试题24:反转链表
- 【剑指offer】面试题 24:反转链表
- 剑指offer面试题24:反转链表
- 剑指Offer 面试题24:反转链表 Java代码实现
- 剑指offer--面试题24:反转链表
- 剑指offer-面试题16-反转链表
- 剑指offer——面试题16:反转链表
- leetcode206/92---Reverse Linked List I/II(反转链表)
- 剑指offer-面试题16.反转链表
- 剑指Offer---面试题16:反转链表
- [LeetCode-206] Reverse Linked List(链表反转)
- 【剑指offer 面试题16】反转链表
- LeetCode206——Reverse Linked List 反转链表
- Leetcode 206 反转链表 Java
- 【剑指Offer】面试题16:反转链表
- 【剑指offer】面试题16:反转链表
- LeetCode探索之旅(60)-206反转链表
- leetcode206 反转链表
- 【剑指offer】3.4代码的鲁棒性——面试题16:反转链表