25. Reverse Nodes in k-Group

来源:互联网 发布:linuxmint优化 编辑:程序博客网 时间:2024/05/29 17:39

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

public class Solution {public ListNode reverseKGroup(ListNode head, int k) {if (isValidSection(head, k) == false)return head;ListNode cur = head;ListNode prev = null, next = null;ListNode temp = cur;int count = k;//用next一个一个的去读取原链表,用prev去读取数据重新生成一个链表while (count > 0) {next = cur.next;cur.next = prev;prev = cur;cur = next;count--;}temp.next = reverseKGroup(cur, k);//递归return prev;}//由于题目是重复进行某个动作,肯定要用递归,输入数据的判断跟后面递归做的判断相似,就写成一个方法//k比ListNode的个数小,则返回false,否则truepublic static boolean isValidSection(ListNode node, int k) {ListNode cur = node;while (cur != null && k > 0) {cur = cur.next;k--;}if (k > 0)return false;return true;}}




0 0