每隔k次反转一次 链表_给定一个链表,要求每隔k个元素反转 | 学步园

给定一个链表,要求每隔k个元素反转,public void kReverse(Node node, int k)

即链表为1->2->3->4->5->6->7->8

当k=2时,链表为2->1->4->3->6->5->8->7

当k=5时,链表5->4->3->2->1->6->7->8

class Node {

public T data;

public Node next;

Node(T dataPortion) {

data = dataPortion;

next = null;

}

Node(T dataPortion, Node nextNode) {

data = dataPortion;

next = nextNode;

}

}

public class ListKReverse {

public static void main(String[] args) {

ListKReverse s = new ListKReverse();

Node n1 = new Node(1);

Node n2 = new Node(2);

Node n3 = new Node(3);

Node n4 = new Node(4);

Node n5 = new Node(5);

Node n6 = new Node(6);

Node n7 = new Node(7);

Node n8 = new Node(8);

n1.next = n2;

n2.next = n3;

n3.next = n4;

n4.next = n5;

n5.next = n6;

n6.next = n7;

n7.next = n8;

Node head = s.ReverseInGroups(n1, 4);

while (head != null) {

System.out.print(head.data+" ");

head = head.next;

}

System.out.println();

}

public Node ReverseInGroups(Node current, int k) {

if (current == null || current.next == null ) return current;

int n=0;

Node oldHead=current;

while(current!=null)

{

current=current.next;

n++;

}

System.out.println(n);

int reverseNum=n/k;

current=oldHead;

Node newHead = current;

Node previousGroupTail = null;

int count = 1;

int num=0;

while (current != null&&num

Node groupTail = current;

Node prev = null;

Node next = null;

for (int i = 1; i <= k && current != null; i++) {

next = current.next;

current.next = prev;

prev = current;

current = next;

}

if (count == 1) {

newHead = prev;

count++;

}

if (previousGroupTail != null) {

previousGroupTail.next = prev;

}

previousGroupTail = groupTail;

num++;

}

if(current!=null)

if (previousGroupTail != null)

previousGroupTail.next = current;

return newHead;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值