链表---每次翻转K个

注意点:需要保存翻转的开始以及结束节点

两个一组进行操作
public ListNode swapPairs(ListNode head) {
        // write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode p = dummy;
        while (p != null && p.next != null && p.next.next != null) {
            ListNode p1 = p.next;
            ListNode p2 = p.next.next;
            ListNode temp = p2.next;
            p2.next = p1;
            p1.next = temp;
            p.next = p2;
            p = p1;
        }
        return dummy.next;
    }

另外一种写法

public ListNode swapPairs(ListNode head) {
        // Write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        ListNode p = dummy;
        dummy.next = head;
        ListNode p1 = dummy.next;
        ListNode p2 = dummy.next.next;
        while (p1 != null && p2 != null) {
            ListNode temp = p2.next;
            p.next = p2;
            p2.next = p1;
            p1.next = temp;

            if (temp == null) {
                break;
            }
            p1 = temp;
            p2 = temp.next;
            p = p.next.next;
        }

        return dummy.next;
    }
public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k < 1) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode p = dummy;
        while (p.next != null) {
            int n = k;
            ListNode q = p.next;
            ListNode start = p.next;
            while (q != null && n  > 1) {
                q = q.next;
                n--;
            }
            if (n > 1 || q == null) {
                break;
            } else {
                ListNode end = q.next;
                ListNode newhead = null;
                ListNode newend = start;
                while (start != end) {
                    ListNode t = start.next;
                    start.next = newhead;
                    newhead = start;
                    start = t;
                } //拼接新的头、尾,把当前游标移动到新的尾。
                p.next = newhead;
                newend.next = end;
                p = newend;
            }
        }
        return dummy.next;
    }

猜你喜欢

转载自blog.csdn.net/l1394049664/article/details/81369409
今日推荐