单链表每隔k个节点反转

一道面试题,第一次碰到这道题的时候 要求10分钟之内手写代码实现,当时没写出来,后来花点时间把过程梳理一遍,也挺简单的.......

思路就是在原来单链表反转的基础上,加几个控制参数,记录几个关键节点。

每k个为一组。

先自定义一个Node类:

public class Node {
    private int data;
    private Node next;

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

    public Node() {
    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", next=" + next +
                '}';
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

实现代码:

public class LinkReverse2 {

    public static Node newLink(int n){
        Node head = new Node();
        head.setData(1);
        head.setNext(null);
        Node tmp = head;
        for(int i=2;i<=n;i++){
            Node newNode = new Node();
            newNode.setData(i);
            newNode.setNext(null);
            tmp.setNext(newNode);
            tmp = newNode;
        }
        return head;
    }

    public static void main(String[] args) {
        Node node = newLink(10);
        pritNode(node);
        Node node1 = reverseKLink(node,3);
        pritNode(node1);

    }
    public static void pritNode(Node head){
        Node temp = head;
        while(temp !=null){
            System.out.print(temp.getData()+"->");
            temp = temp.getNext();
        }
        System.out.println();
    }

    /*public static Node reverseLink(Node head){
        Node pre=null,cur=head,next=null;
        while(cur!=null){
            next=cur.getNext();
            cur.setNext(pre);
            pre=cur;
            cur=next;
        }
        return pre;
    }*/


    public static Node reverseKLink(Node head,int k){
        Node pre=null,cur=head,next=null;

        Node pnext=null,global_head=null;
        int i=0;
        Node tmp=null;

        while(cur!=null){
            next = cur.getNext();

            if(tmp==null) tmp=cur;   //tmp记录当前组反转完最后一个节点
            if(pnext!=null) pnext.setNext(cur);  //pnext是上一组反转完最后一个节点

            cur.setNext(pre);
            pre=cur;
            cur = next;

            i++;
            if(i>=k){  //当前组反转完成的时候
                if(global_head==null){
                    global_head=pre;
                }
                if(pnext!=null){  //将上一组反转完的最后一个节点指向 当前组反转完后的第一个节点
                    pnext.setNext(pre);
                }
                pnext=tmp; //迭代

                i=0;  //新的一组反转时 关键数据初始化
                tmp=null;
                pre=null;
            }
        }
        return global_head;
    }
}

思路图:

猜你喜欢

转载自www.cnblogs.com/f-society/p/10812428.html