单链表每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;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值