链表问题

1.链表的反转

    public ListNode ReverseList(ListNode head){
        if(head==null){
            return head;
        }
        ListNode pNode=head;
        ListNode pre=null;
        ListNode newHead=null;
        for(pNode!=null){
            ListNode pNext=pNode.next;
            if(pNext==null){
                newHead=pNode;
            }
            pNode.next=pre;
            pre=pNode;
            pNode=pNext;
        }
        return  newHead;
    }

2.一个链表有环,找出环入口

//1.首先定义快慢指针,快的走两步,慢的走一步。第一次相遇后快走的距离入口和慢指针初始位置到入口的距离相等。2(x+m)=x+m+l+m  得到x=l
    public ListNode findLoopPort(ListNode head){
        ListNode slow=head;
        ListNode fast=head;
        while (fast!=null&&fast.next!=null){
            slow=head.next;
            fast=fast.next.next;
            if(slow==fast){
                break;
            }
        }
        if(fast==null||fast.next==null){
            return  null;
        }
        slow=head;
        while (slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return  slow;
    }

2.部分链表反转

    /**
     * 反转部分链表1->2->3->4->5->null from 2 to 4。反转后变成1-4>3->2->5->null
     */
    public static ListNode reversePart(ListNode head,int from,int to){
        int len=0;
        ListNode node1=head;
        ListNode fPre=null;
        ListNode tPos=null;
        while (node1!=null){
            len++;
            fPre=len==from-1?node1:fPre;
            tPos=len==to+1?node1:tPos;
            node1=node1.next;
        }
        if(from>to||from<1||to>len){
            return head;
        }
        node1=fPre==null?head:fPre.next;
        ListNode node2=node1.next;
        node1.next=tPos;
        ListNode next=null;
        while (node2!=tPos){
            next=node1.next;
            node2.next=node1;
            node1.next=node2;
            node2=next;
        }
        if(fPre!=null){
            fPre.next=node1;
            return  head;
        }
        return  node1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值