Reverse Second Half of a Linked List

来源:互联网 发布:同志长得帅体验知乎 编辑:程序博客网 时间:2024/05/21 06:17


class ListNode {int val;ListNode next;ListNode(int x) { val = x; }}public class ReverseSecondHalfofLinkedList {public static ListNode reverseSecondHalf(ListNode head) {if(head == null || head.next == null)return head;        ListNode slow = head, fast = slow.next;        while(fast.next != null && fast.next.next != null) {            slow = slow.next;            fast = fast.next.next;        }        ListNode pre = null, cur = slow.next;        while(cur != null) {            ListNode next = cur.next;            cur.next = pre;            pre = cur;            cur = next;        }        slow.next = pre;        return head;}}