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
  • 相关阅读:
    Bzoj1027 [JSOI2007]合金
    Bzoj4318 OSU!
    Bzoj3931 [CQOI2015]网络吞吐量
    Bzoj3551 [ONTAK2010]Peaks加强版
    Bzoj3545 [ONTAK2010]Peaks
    Bzoj4031 [HEOI2015]小Z的房间
    Bzoj3613 [Heoi2014]南园满地堆轻絮
    Bzoj4516 [Sdoi2016]生成魔咒
    HDU1847 Good Luck in CET-4 Everybody!
    HDU1846 Brave Game
  • 原文地址:https://www.cnblogs.com/theskulls/p/4890108.html
Copyright © 2011-2022 走看看