LeetCode_OJ【25】Reverse Nodes in k-Group

来源:互联网 发布:个性名片制作软件 编辑:程序博客网 时间:2024/05/22 07:07

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

此题难度为hard,虽然思路很常见,但是能一次性不出错地写出来确实不太容易(可怜我WA了好多次 T_T)。这种题目还是很能考察一个人基本功的。

对于每次要操作的K个元素,记录这K个元素的第一个为start,最后一个元素为end,start前面的元素为pre,首先处理start和pre元素,处理start的时候要记录start.next,否则链表就断掉了,后面的直接丢失了,然后处理start至end之间的所有节点。

具体代码如下:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        if(k < 2){            return head;        }ListNode dummy = new ListNode(-1);dummy.next = head;ListNode pre = dummy, end = dummy;while(end != null){for(int i = 0 ; i < k && end != null ; i++ ){end = end.next;}if(end == null){break;}ListNode start = pre.next;pre.next = end;pre = start;ListNode cur = start.next;               //要处理start节点则需要保存start.next节点start.next = end.next;while(cur != end){ListNode after = cur.next;       //要处理cur节点则需保存cur.next节点cur.next = start;start = cur;cur = after;after = after.next;}end.next = start;end = pre;}        return dummy.next;    }}


0 0
原创粉丝点击