zoukankan      html  css  js  c++  java
  • lintcode :链表插入排序

    题目:

    用插入排序对链表排序

    样例

    Given 1->3->2->0->null, return 0->1->2->3->null

    解题:

    感觉很简单,但是没有写出来,链表的操作还不行的,九章程序

    Java程序:

    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */ 
    public class Solution {
        /**
         * @param head: The first node of linked list.
         * @return: The head of linked list.
         */
        public ListNode insertionSortList(ListNode head) {
            // write your code here
            ListNode dummy = new ListNode(0);
    
            while (head != null) {
                ListNode node = dummy;
                while (node.next != null && node.next.val < head.val) {
                    node = node.next;
                }
                ListNode temp = head.next;
                head.next = node.next;
                node.next = head;
                head = temp;
            }
    
            return dummy.next;
        }
    }
    View Code

    总耗时: 2735 ms

    Python程序:

    """
    Definition of ListNode
    class ListNode(object):
    
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    """
    class Solution:
        """
        @param head: The first node of linked list.
        @return: The head of linked list.
        """ 
        def insertionSortList(self, head):
            # write your code here
            if head == None:
                return head
            p = ListNode(0)
            while head!=None:
                node = p
                while node.next!=None and node.next.val<head.val:
                    node = node.next
                tmp = head.next
                head.next = node.next
                node.next = head 
                head = tmp
            return p.next 
    View Code
  • 相关阅读:
    oracle锁表查询,资源占用,连接会话,低效SQL等性能检查
    oracle临时表
    oracle列转行
    oracle数据库查询重复记录
    查找mysql的cnf文件位置
    Nginx反向代理,负载均衡,redis session共享,keepalived高可用
    Linux 软件安装
    Linux上网设置
    c#学习内容
    PHP八大设计模式
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4890108.html
Copyright © 2011-2022 走看看