Reverse Second Half of Linked List

亚麻的一道OA题,觉得有必要再熟练几次。这个题主要考察两个地方。1.如何找到链表的中间位置,2.如何对链表进行反转。分开的两个部分都可以在leetcode的上找到类似的题,思路也比较清晰,注意奇数的时候中间点也需要翻转就好。

代码:

  public ListNode reverseList(ListNode head) {
        if(head == null) return null;
        //因为中间也需要变,所以要添加dummy
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode slow = dummy;
        ListNode fast = dummy;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        //找到中间的位置了slow 右侧开始反转
        ListNode pre = null;
        ListNode cur = slow.next;

        while(cur != null){
            ListNode temp = cur.next;

            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        slow.next = pre;
        return head;
    }

public static void main(String[] args) {
        reverseList list = new reverseList();
        ListNode one = new ListNode(1);
        ListNode two = new ListNode(2);
        ListNode three = new ListNode(3);
        ListNode four = new ListNode(4);
        ListNode five = new ListNode(5);
       // ListNode six = new ListNode(6);
        one.next = two;
        two.next = three;
        three.next = four;
        four.next = five;
        //five.next = six;
        list.reverseList(one);
        ListNode p = one;
        while(p != null){
            System.out.print(p.val+" ");
            p = p.next;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值