25. Reverse Nodes in k-Group

来源:互联网 发布:指纹软件网吧推销 编辑:程序博客网 时间:2024/05/16 09:27

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

k is a positive integer and is less than or equal to the length of the linked 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

这道题我的思路是,首先统计出链表的长度,然后对链表的前k个元素进行翻转,再翻转前,需要记录此时的head,即为下次的tail,同时给定一个prev为null。随后进行while循环,一直到剩下的链表长度不足k为止,此时需要记录翻转部分的head为翻转完成后的tmptail,在翻转完成后需要将tail.next指向prev,完成链表的串接,同时将tail进行更新为tmptail.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        if (head == null) {            return head;        }        ListNode tmp = head;        int len = 0;        while (tmp != null) {            tmp = tmp.next;            len++;        }        if (k > len) {            return head;        }        ListNode tail = head;        ListNode prev = null;        ListNode node = new ListNode(0);        for (int i = 0; i < k; i++) {            node = head.next;            head.next = prev;            prev = head;            head = node;        }        len = len - k;        ListNode dummy = prev;        while (len - k >= 0) {            prev = null;            ListNode tmpTail = head;            for (int i = 0; i < k; i++) {                node = head.next;                head.next = prev;                prev = head;                head = node;            }            tail.next = prev;            tail = tmpTail;            len = len - k;        }        tail.next = node;        head = prev;        return  dummy;    }}

这道题用递归来做,也很简单,注意要把head=curr再返回

if (head == null) {            return head;        }        ListNode curr = head;        int count = 0;        while (curr != null && count != k) {            curr = curr.next;            count++;        }        if (count == k) {            curr = reverseKGroup(curr, k);            for (int i = 0; i < k; i++) {                ListNode node = head.next;                head.next = curr;                curr = head;                head = node;            }            head = curr;        }        return head;


原创粉丝点击