單鏈表每k個節點一組進行反轉(最後不足k個也反轉)

一道面試題,第一次碰到這道題的時候 要求10分鐘以內手寫代碼實現,當時沒寫出來,後來花點時間把過程梳理一遍,也挺簡單的.......node

思路就是在原來單鏈表反轉的基礎上,加幾個控制參數,記錄幾個關鍵節點。面試

每k個爲一組。ide

 

先自定義一個Node類:this

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;
    }
}

 

實現代碼:spa

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;
    }
}

 

思路圖:code

相關文章
相關標籤/搜索