Python-剑指offer(15,16)反转链表,合并两个链表

简介: Python-剑指offer(15,16)反转链表,合并两个链表

题目:输入一个链表,反转链表后,输出新链表的表头。

环境:Python2.7.3

# -*- 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
        newHead = None
        while pHead:
            temp = pHead.next
            pHead.next = newHead
            newHead = pHead
            pHead = temp
        return newHead

题目:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        if not pHead1:
            return pHead2
        if not pHead2:
            return pHead1
        if pHead1.val < pHead2.val:
            pres = pHead1
            pres.next = self.Merge(pHead1.next, pHead2)
        else:
            pres = pHead2
            pres.next = self.Merge(pHead1, pHead2.next)
        return pres


相关文章
|
16天前
|
Python
Python中 合并字典
【6月更文挑战第15天】
10 4
|
27天前
|
SQL 算法 数据可视化
LeetCode题目92:反转链表ll 【python 递归与迭代方法全解析】
LeetCode题目92:反转链表ll 【python 递归与迭代方法全解析】
|
17天前
|
Python
用python写单链表
用python写单链表
|
19天前
|
Python
【代码】Python实现Excel数据合并
【代码】Python实现Excel数据合并
17 0
|
23天前
23.合并K个升序链表
23.合并K个升序链表
|
28天前
|
算法 数据挖掘 Python
LeetCode题目25 hard:K个一组翻转链表 【分治策略 Python】
LeetCode题目25 hard:K个一组翻转链表 【分治策略 Python】
|
28天前
|
存储 SQL 算法
|
28天前
|
存储 算法 数据挖掘
Leetcode二十三题:合并K个升序链表【22/1000 python】
Leetcode二十三题:合并K个升序链表【22/1000 python】
|
28天前
|
SQL 算法 数据挖掘
LeetCode 二十一:合并两个有序链表 【python】
LeetCode 二十一:合并两个有序链表 【python】