【剑指offer】面试题 24:反转链表
2017-07-18 13:46
267 查看
题目描述
输入一个链表,反转链表后,输出链表的所有元素。
时间限制:1秒 空间限制:32768K 热度指数:137078
本题知识点: 链表
思路
pHead始终指向要反转的节点,last 指向反转后的首节点,
每反转一个节点,把 pHead 节点的下一个节点指向 last,
last 指向 pHead 成为反转后的首节点,再把 pHead 向前移动一个节点直至None结束;
参考代码
版本一
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
last = None
while pHead:
tmp = pHead.next
pHead.next = last
last = pHead
pHead = tmp
return last
版本二
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
pReversedHead = None
pNode = pHead
pPrev = None
while pNode != None:
pNext = pNode.next
if pNext == None:
pReversedHead = pNode
pNode.next = pPrev
pPrev = pNode
pNode = pNext
return pReversedHead
def ReverseListRec(self, pHead):
if not pHead or not pHead.next:
return pHead
else:
pReversedHead = self.ReversedList(pHead.next)
pHead.next.next = pHead
pHead.next = None
return pReversedHead
输入一个链表,反转链表后,输出链表的所有元素。
时间限制:1秒 空间限制:32768K 热度指数:137078
本题知识点: 链表
思路
pHead始终指向要反转的节点,last 指向反转后的首节点,
每反转一个节点,把 pHead 节点的下一个节点指向 last,
last 指向 pHead 成为反转后的首节点,再把 pHead 向前移动一个节点直至None结束;
参考代码
版本一
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
last = None
while pHead:
tmp = pHead.next
pHead.next = last
last = pHead
pHead = tmp
return last
版本二
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
pReversedHead = None
pNode = pHead
pPrev = None
while pNode != None:
pNext = pNode.next
if pNext == None:
pReversedHead = pNode
pNode.next = pPrev
pPrev = pNode
pNode = pNext
return pReversedHead
def ReverseListRec(self, pHead):
if not pHead or not pHead.next:
return pHead
else:
pReversedHead = self.ReversedList(pHead.next)
pHead.next.next = pHead
pHead.next = None
return pReversedHead
相关文章推荐
- 【剑指offer】面试题24:反转链表
- 剑指Offer 面试题24:反转链表 Java代码实现
- 剑指offer--面试题24:反转链表
- 剑指offer面试题24:反转链表
- 剑指offer-面试题16.反转链表
- 剑指offer-面试题16.反转链表
- 剑指offer-面试题16-反转链表
- 剑指offer面试题16之反转链表
- 剑指offer面试题16 反转链表
- 剑指offer-面试题 16:反转链表
- 剑指offer_面试题16_反转链表(两种方法)
- [剑指offer][面试题16]反转链表
- 【剑指Offer】面试题16:反转链表
- 剑指offer-面试题16-反转链表
- 剑指Offer面试题16 反转链表
- [剑指offer]面试题16:反转链表
- 剑指Offer面试题:15.反转链表
- 剑指offer--面试题16: 反转链表
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- 剑指Offer面试题16(Java版):反转链表