**
背景
**
前几日,看到一道面试题,每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;
}
}