雾雨人偶店

Java单链表

LEETCODE刷到单链表排序,才知道单链表是需要自己构造的,双链表和链图都是IDE自带

构造代码如下

/**

 * Definition for singly-linked list.

 * public class ListNode {

 *     int val;//每个节点的值,不一定是int

 *     ListNode next;//每个节点

 *     ListNode(int x) { val = x; }//节点的构造函数

 * }

 */


利用递归的排序如下:

class Solution {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if(l1==null)

            return l2;

        if(l2==null)

            return l1;

        if(l1.val<l2.val)

        {

            l1.next=mergeTwoLists(l1.next,l2);

            return l1;

        }

        else

        {

            l2.next=mergeTwoLists(l1,l2.next);

            return l2;

        }

    }

}

递归用吼,天下我有(。


评论

热度(1)