Reverse Nodes in k-Group

来源:互联网 发布:网络嗅探器用哪个好 编辑:程序博客网 时间:2024/05/27 20:30

题目描述

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

解题思路

  • 如果i % k 不等0, 就直接head = head.next;
  • 如果i % k 等于0, 就执行翻转

代码实现

    public ListNode reverseKGroup(ListNode head, int k) {        if(head == null){            return null;        }        if(k == 1)            return head;        int i = 0;        //链表增加头结点  以便于统一化操作        ListNode dummy = new ListNode(0);        dummy.next = head;        ListNode pre = dummy;        //注意边界条件的判断        while(head != null){            i++;            if(i % k == 0){                pre = reverseK(pre, head.next);                head = pre.next;            }else {                head = head.next;            }        }        return dummy.next;    }    /**     * 函数功能:链表翻转   1->2->3->4->5  当tail为5时    4->3->2->1->5     * first second 是相邻的两个元素     * pre 相当于头结点 不会改变     * tail 相当于尾节点 用于判断结束     * pre 和 first 指向的节点不会改变, 但是second指向的节点会改变     */    public ListNode reverseK(ListNode pre, ListNode tail){        ListNode first = pre.next;        ListNode second  = first.next;        while(second != tail){            first.next = second.next;            second.next = pre.next;            pre.next = second;            second = first.next;        }        return first;    }
0 0