LeetCode 25. Reverse Nodes in k-Group

来源:互联网 发布:python作品 编辑:程序博客网 时间:2024/06/18 03:48

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

链表局部翻转的题,不能new新链表。

由于每次只反转k个,链表长n,那么可以每次处理k个,最后处理一下尾部即可。

reverseK2用来每次处理k个,这里用了递归,不需要new对象。


在调用reverseK2时,还是要先遍历链表,移动k次,找到尾部及每次剩余链表的头。


在做完reverseK2后,要将处理后的尾部与剩余链表首部相连,这里比较容易错,试了几次才写对

 

 public ListNode reverseKGroup(ListNode head, int k) {      if(head==null||head.next==null||k<2)return head;        int count=1;    ListNode cur=head;    while(count<k&& cur!=null){//先看有没有k个    cur=cur.next;    count++;            }    if(count<k||cur==null)return head;    ListNode newHead=cur.next;    reverseK2(head,k);    ListNode lastTail = head;    head = cur;    if(newHead==null){    //这里还要处理一下tail    lastTail.next=null;    return head;        }    while(1==1){    count=1;    cur=newHead;    while(count<k){//先看有没有k个        if(cur!=null){        cur=cur.next;        count++;        }        else{        lastTail.next=newHead;        return head;        }        }    if(count<k||cur==null){    lastTail.next=newHead;    return head;    }    ListNode temp=newHead;    newHead=cur.next;        reverseK2(temp,k);        lastTail.next=cur;        lastTail = temp;        }            }    public static ListNode reverseK2(ListNode head, int k) {    if(head==null||head.next==null||k<2)return head;     reverseK2(head.next,k-1);     head.next.next=head;     return head;    }