Linked Lists - Sorted Insert

13 篇文章 0 订阅
6 篇文章 0 订阅

https://www.codewars.com/kata/linked-lists-sorted-insert/train/python

Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list.

sortedInsert(1 -> 2 -> 3 -> null, 4) === 1 -> 2 -> 3 -> 4 -> null)
sortedInsert(1 -> 7 -> 8 -> null, 5) === 1 -> 5 -> 7 -> 8 -> null)
sortedInsert(3 -> 5 -> 9 -> null, 7) === 3 -> 5 -> 7 -> 9 -> null)

在排好序的链表中插入一个新元素。

我的算法:


class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None


def sorted_insert(head, data):
    h = head   
    new_node = Node(data)
    if not head:
        return new_node
    while h.next:
        if h.next.data>data:
            break
        h = h.next
    new_node.next = h.next
    h.next = new_node
    if h.data>data:
        h.data,new_node.data = new_node.data,h.data
    return head
        
              
        
    

找到大于它的第一个节点Q,然后插入到Q前面,如果Q之前的节点 P的值比新节点data的值要大,那就将P的值和新节点的值交换

 

大神的算法

class Node(object):
  def __init__(self, data, nxt = None):
    self.data = data
    self.next = nxt
    
def sorted_insert(head, data):
  if not head or data < head.data: return Node(data, head)
  else:
    head.next = sorted_insert(head.next, data)
    return head

用了递归调用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值