Java-单链表每K个值逆序

2021-03-09  本文已影响0人  坑逼的严

记录一下
将给出的链表中的节点每k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
要求空间复杂度O(1)
例如:
给定的链表是1→2→3→4→5
对于 k = 2, 你应该返回 2→1→4→3→5
对于 k = 3, 你应该返回 3→2→1→4→5

public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        //如果头为空,并且头的下一个节点为空,那么不需要翻转直接返回
        if (head == null || head.next == null)
        return head;
        //新起一个变量,接收head,防止head值被修改
        ListNode curHead = head;
        //找到下一个链表中K个值以后的head
        for(int x=1 ; x<k; x++){
            if(curHead != null){
                curHead = curHead.next;
            }
        }
        //如果不足K个值,那么都照着原样返回
        if(curHead == null){
            return head;
        }
        //记录下一次K个值后的头
        ListNode temp = curHead.next;
        //切断原有的连接
        curHead.next = null;
        //翻转这一段的K个值
        ListNode newHead = reverse(head);
        //翻转下一个K段值
        ListNode newTemp = reverseKGroup(temp,k);
        //翻转后的K个值,重新连接
        ListNode tempNode = newHead;
        for(int x = 1; x< k;x++){
            tempNode = tempNode.next;
        }
        tempNode.next = newTemp;
        return newHead;
}
public ListNode reverse(ListNode head){
        if (head == null || head.next == null)
        return head;
        ListNode newNode = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return newNode;
}
上一篇 下一篇

猜你喜欢

热点阅读