java链表按第k个值反转,【Java实现】链表反转、以k个为一组反转链表,不足k个也反转、以k个为一组反转链表,不足k个不反转...

/*反转链表,输出新链表的表头*/

public static ListNode ReverseList(ListNode head) {

if(head == null) return null;

ListNode node = head;

ListNode pre = null;

while(node != null){//当node的下一个节点为空的时候,意味着到了尾节点,但是返回的是pre,所以要先使pre = node,则为node!=null

ListNode next = node.next;//要先保存node的下一个节点才能让node指向前一个节点

if(next == null)

head = node;//当node的下一个节点为空的时候,保存新链表的表头

node.next = pre;//将node指向前一个节点

pre = node;//继续转下一个节点,pre+1,则前一个节点存为node

node = next;//当前节点继续加1

}

return head;

}

//【扩展】以k个反转链表,不足k个也反转

public static ListNode ReverseList_All_k(ListNode head, int k){

if (head == null)

return head;

ListNode cur = head;

ListNode pre = null;//前一个元素

int count = 0;

while (count < k && cur != null) {

ListNode reCur = cur;//保留当前的元素,为了能找到下一个元素

reCur.next = pre;

pre = reCur;//pre保留的是最后一个要操作的元素

cur = cur.next;

count++;

}

if (cur != null)

head.next = ReverseList_All_k(cur, k);

return pre;

}

//【扩展】以k个反转链表,不足k个不反转

public static ListNode ReverseList_buzu_k(ListNode head, int k){

if(head == null)

return head;

ListNode cur = head;

ListNode pre = null;

int count = 0;

if(getLength(cur)>=k){//判断当前链表长度

while(count < k && cur != null){

ListNode reCur = cur;

reCur.next = pre;

pre = reCur;

cur = cur.next;

count++;

}

if(cur != null)

head.next = ReverseList_buzu_k(cur, k);

return pre;

}

return cur;

}

public static int getLength(ListNode head){

ListNode node = head;

int count = 0;

while(node != null){

count++;

node = node.next;

}

return count;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值