單鏈表每k個節點反轉一次

**

背景

**
前幾日,看到一道面試題,每k個結點反轉一次鏈表,要求輸出反轉後的鏈表。
題目意思如下:
原鏈表:1,2,3,4,5,6,7,8
k = 3
新鏈表:3,2,1,6,5,4,8,7

**

思路分析

**
如圖所示鏈表
在這裏插入圖片描述
k=3的時候,每次反轉三個節點(1,2,3),操作涉及四個節點(1,2,3,4),最後節點1的next指向節點4,每k個節點反轉一次。遞歸下去
在這裏插入圖片描述
單鏈表反轉可以參考我的另一篇博客:單鏈表反轉
**

代碼實現

**

/**
 * author : panther
 * 1->2->3->4->5->6->7->8->null
 * 3->2->1->6->5->4->8->7->null
 * date : 2020/4/10
 */
public class NodeLinkPractice {
    public static void main(String[] args) {
        Node node8 = new Node(8, null);
        Node node7 = new Node(7, node8);
        Node node6 = new Node(6, node7);
        Node node5 = new Node(5, node6);
        Node node4 = new Node(4, node5);
        Node node3 = new Node(3, node4);
        Node node2 = new Node(2, node3);
        Node node1 = new Node(1, node2);
        Node result = reverseLink(node1, 3);
        while (result != null) {
            System.out.print(result.value + " ");
            result = result.next;
        }
        System.out.println();
    }
    //head:頭節點,k:反轉的節點個數
    private static Node reverseLink(Node head, int k) {
        if (k <= 1 || head == null) { //反轉個數<=1或者鏈表爲空
            return head;
        }
        int cnt = 0;
        Node start = head,resulthead = null,segnext = null;
        while (head != null) { //遍歷鏈表
            ++cnt;
            if (cnt == k) { //達到需要反轉的個數
                Node next = head.next;
                Node hh = reverseLink(start, next); //鏈表操作的起始節點和終點
                if (resulthead == null) {
                    resulthead = hh;
                    segnext = start;
                } else {
                    segnext.next = hh;
                    segnext = start;
                }
                start = next;
                cnt = 0;
                head = next;
            } else {
                head = head.next;
            }
        }
        if (cnt != 0) {
            Node hh = reverseLink(start, null);
            if (resulthead == null) {
                resulthead = hh;
            } else {
                segnext.next = hh;
            }
        }
        return resulthead;
    }
    //鏈表反轉(ex:是->2->3->4轉換成3->2->1->4)
    private static Node reverseLink(Node head, Node tail) {
        Node prev = null,cur = head,next = null;
        while (cur != tail) {
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        head.next = tail;
        return prev;
    }
}
class Node {
    int value;
    Node next;
    public Node(int value, Node next) {
        this.value = value;
        this.next = next;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章