leetcode链表题目 翻转 回文 排序

排序链表

要求复杂度nlogn

class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        ListNode p1=head;
        ListNode p2=head;

        while(p2.next!=null&&p2.next.next!=null){
            p1=p1.next;
            p2=p2.next.next;
        }
//断开链表
        ListNode cur=p1;
        p1=p1.next;
        cur.next=null;
//递归处理
        ListNode L=sortList(head);
        ListNode R=sortList(p1);
        return merge(L,R);
    }

    public ListNode merge(ListNode l,ListNode r){
        ListNode pre=new ListNode(0);
        ListNode m=pre;
        while(l!=null&&r!=null){
            if(l.val<r.val){
                m.next=l;
                m=m.next;
                l=l.next;
            }
            else{
                m.next=r;
                m=m.next;
                r=r.next;
            }
        }
        if(l!=null){
            m.next=l;
        }
        if(r!=null){
            m.next=r;
        }
        return pre.next;
    }
}

判断 是否为回文链表

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null){
            return true;
        }
        ListNode cur=new ListNode(0);
        cur.next=head;
        ListNode p1=cur;
        ListNode p2=head;
        while(p2!=null&&p2.next!=null){
            p1=p1.next;
            p2=p2.next.next;
        }
        ListNode res=reverse(p1.next);
        p1.next=null;//断开来
        while(head!=null&&res!=null){
            if(head.val!=res.val){
                return false;
            }
            else{
                head = head.next;
                res = res.next;
            }
        }
        return true;

    }
//反转链表
    public ListNode reverse(ListNode head){
        ListNode pre=null;
        ListNode cur=head;
        ListNode ne=null;
        while(cur!=null){
            ne=cur.next;
            cur.next=pre;
            pre=cur;
            cur=ne;
        }
        return pre;
    }
}

k个一组翻转链表

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
       if(head==null) return head;
       ListNode cur=head;
       int i=k;
       while(i>0&&cur!=null){
           cur=cur.next;
           i--;
       }
       if(i>0) return head;
       //递归
       ListNode pre=reverseKGroup(cur,k);
       i=k;
       while(i>0){
           ListNode tmp=head.next;
           head.next=pre;
           pre=head;
           head=tmp;
           i--;
       }
       return pre;
}
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值