Invert K Nodes In Linked List(倒置链表的K个节点)

Posted Dream_it_possible!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Invert K Nodes In Linked List(倒置链表的K个节点)相关的知识,希望对你有一定的参考价值。

Question

        Given a linked list, reverse the nodes of a linked list  k at a time and return its modified list. K is a positive integer and is less than or equal to the length of linked list. If the number of nodes is not a mutiple of k then left-out nodes in the end should remain as it is.

example

Input

1->2->3->4->5->null      2

Output

2->1->3->4->5->null 

Input

 1->2->3->4->5->null      4

Output

4->3->2->1->5->null 

Input

1->2->3->4->5->null   6 

Output

1->2->3->4->5->null 

Thinking 

        The question is very similar to Rerverse List ,  but also there are still diference, because it can control the position number of reversal.

        Actually, What we want is that how to point the next of the last elment of the reversed list to the original element in positive position.

        For example, if we want invert 4 elements in linked list,  please see the following diagram.

        we can divide the above process into two steps, first  finding the element with the index 4, and then invert the elment before that index, in this way , The linked list has been split into  two uneven segements.

        int index = 0;
        Node back = new Node(0, null);
        Node b = back;
        while (head != null) {
            if (index == num) {
                //find the target index
                break;
            }
            Node current = head;
            head = head.next;
            current.next = pre;
            pre = current;
            index++;
            // back
            back.next = new Node(current.data, null);
            back = back.next;
        }

        Secondly,  we connect the end of the previous list  to the head of the following list via the next pointer.

        we can use pre.next==null  to judge if it reaches the end of the linked list.

        Node left = pre;
        // 将反转链表的队尾指向head
        while (true) {
            if (pre.next == null) {
                pre.next = head;
                break;
            }
            pre = pre.next;
        }

        If the input number exceeds the specified range, the original linked list should be returned.

Node back = new Node(0, null);
Node b = back;

        It is a good way to back the linked list when we reverse .

  back.next = new Node(current.data, null);
  back = back.next;

         If num>index  ,  Let's return the original linked list.

if (num > index) {
         return b.next;
}

Test

Input

1->2->3->4->5->null   3

Output

3->2->1->4->5->null 

         Finally, we got  what we wanted  from the test! 

 Complete Code

package leetcode100;

/**
 * @author bingbing
 * @date 2021/5/25 0025 22:13
 */
public class ReverseList {

    static class Node {
        Object data;
        Node next;

        public Node(Object data, Node next) {
            this.data = data;
            this.next = next;
        }

        public String traverse() {
            return this.data + "->" + (this.next == null ? "null" : this.next.traverse());
        }
    }


    public static void main(String[] args) {
        Node node5 = new Node(5, null);
        Node node4 = new Node(4, node5);
        Node node3 = new Node(3, node4);
        Node node2 = new Node(2, node3);
        Node head = new Node(1, node2);
        Node res = reverse(head);
        Node next = res.next;
        System.out.print(res.data + "->");
        while (next != null) {
            System.out.print(next.data + "->");
            next = next.next;
        }
        System.out.print("NULL");
        System.out.println("");

        // 反转指定位数的节点
        Node h = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null)))));
        Node result = reverseListSpecifyNumber(h, 3);
        System.out.println(result.traverse());

    }

    /**
     * 反转链表
     *
     * @param head
     * @return
     */
    public static Node reverse(Node head) {
        Node pre = null;
        while (head != null) {
            Node current = head;
            head = head.next;
            current.next = pre;
            pre = current;
        }
        return pre;
    }


    public static Node reverseListSpecifyNumber(Node head, int num) {
        if (num <= 0) {
            throw new IllegalArgumentException("illegal argument!");
        }
        Node pre = null;
        int index = 0;
        Node back = new Node(0, null);
        Node b = back;
        while (head != null) {
            if (index == num) {
                //find the target index
                break;
            }
            Node current = head;
            head = head.next;
            current.next = pre;
            pre = current;
            index++;
            // back
            back.next = new Node(current.data, null);
            back = back.next;
        }
        // 如果超出范围,那么保持原样
        if (num > index) {
            return b.next;
        }
        Node left = pre;
        // 将反转链表的队尾指向head
        while (true) {
            if (pre.next == null) {
                pre.next = head;
                break;
            }
            pre = pre.next;
        }
        return left;


    }

}

Tips:  The above code contains how to reverse linked list, wish you good luck!

以上是关于Invert K Nodes In Linked List(倒置链表的K个节点)的主要内容,如果未能解决你的问题,请参考以下文章

Swap Two Nodes in Linked List

lintcode-medium-Swap Two Nodes in Linked List

[刷题] LeetCode 237 Delete Nodes in a Linked List

[GeeksForGeeks] Swap nodes in a single linked list by changing links

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k

Chapter six Linked List & Array(链表与数组)