博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 25: Reverse Nodes in k-Group
阅读量:6969 次
发布时间:2019-06-27

本文共 1647 字,大约阅读时间需要 5 分钟。

hot3.png

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        if(head == null)      {          return null;      }      ListNode dummy = new ListNode(0);      dummy.next = head;      int count = 0;      ListNode pre = dummy;      ListNode cur = head;      while(cur != null)      {          count ++;          ListNode next = cur.next;          if(count == k)          {              pre = reverse(pre, next);              count = 0;             }          cur = next;      }      return dummy.next;      }    private ListNode reverse(ListNode pre, ListNode end)      {          if(pre==null || pre.next==null)              return pre;          ListNode head = pre.next;          ListNode cur = pre.next.next;          while(cur!=end)          {              ListNode next = cur.next;              cur.next = pre.next;              pre.next = cur;              cur = next;          }          head.next = end;          return head;      }  }

转载于:https://my.oschina.net/liusicong/blog/374600

你可能感兴趣的文章
LYNC2013部署系列PART6:边缘部署
查看>>
springmvc的过滤器和拦截器
查看>>
PHP出现Warning: A non-numeric value encountered问题的原因及解决方法
查看>>
取出文本中的图片
查看>>
startService&bindService使用场景的学习理解
查看>>
GSON处理JSON
查看>>
iOS开发之监听键盘高度的变化
查看>>
Day6-Dhcp
查看>>
BFS 两个重要性质
查看>>
Hillstone目的地址转换DNAT配置
查看>>
更完美点的登录
查看>>
HDU 1035 - Robot Motion
查看>>
Sicily 1698. Hungry Cow
查看>>
第一章 Java初步
查看>>
洛谷P2462 [SDOI2007]游戏(哈希+最长路)
查看>>
HDU 1428 漫步校园
查看>>
dispatch_source_create创建定时器和UIWindow创建类似处
查看>>
Java语言基础(九)
查看>>
python基础一 day5 集合
查看>>
Tomcat指定特定JDK版本
查看>>